• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
gw2010
重新编程
博客园    首页    新随笔    联系   管理    订阅  订阅
小练习 登月机器人

  今天看到园子里有一个登月机器人的面试题,于试着写一下,有一点坑爹的地方是if不能起过5个,下面就有这种情况

if(a){
    if(x) code1;
    if(y) code2;
}

这个我改成

if(a && x) code1;
if(a && y) code2;

我这样不是也少了if吗?这坑爹.

下面是一坨C#代码

    public class MoonRabbit
    {
        private string DIR = "NESW";

        private Tuple<int, int> position;//当前位置
        private int direction;//当前的方向

        public MoonRabbit(Tuple<int, int> position, char direction)
        {
            this.position = position;
            this.direction = DIR.IndexOf(direction);
        }

        public void Foo(string instruct)
        {
            char[] ch = instruct.ToArray<char>();

            for (int i = 0, ct = ch.Length; i < ct; i++)
            {
                Rotation(ch[i]);
                Move(ch[i]);
            }
        }

        public void Show()
        {
            Console.WriteLine("当前位置({0},{1}),方向{2}", position.Item1, position.Item2, DIR[direction]);
        }

        private void Rotation(char instruct)
        {
            if (instruct == 'R') direction = (direction + 1) % 4;
            if (instruct == 'L') direction = (direction - 1 + 4) % 4;
        }
        private void Move(char instruct)
        {
            int x = position.Item1;
            int y = position.Item2;

            if (instruct == 'F' && (DIR.IndexOf('E') == direction || DIR.IndexOf('W') == direction))
                x = x + (2 - direction); //13 EW
            if (instruct == 'F' && (DIR.IndexOf('N') == direction || DIR.IndexOf('S') == direction))
                y = y + (1 - direction);//02 NS

            position = new Tuple<int, int>(x, y);
        }
    }

 

声明本博客文章未特殊注明均为原创,转载请注明作者和原地址。 博客地址:http://www.cnblogs.com/gw2010/ 博客首发:http://www.zhou2019.cn
posted on 2014-03-05 13:41  gw2010  阅读(151)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3