找到合适和正确目的地的算法

Algorithm to find appropriate-and-correct destination

A robot lands on Mars, which happens to be a cartesian grid; assuming that we hand the robot these instructions, such as LFFFRFFFRRFFF, where "L" is a "turn 90 degrees left", "R" is a "turn 90 degrees right", and "F" is "go forward one space, please write control code for the robot such that it ends up at the appropriate-and-correct destination, and include unit tests.

这是使用命令 "FF":

的示例输出
[0, 2]

我可以在 Google 上找到这个问题的解决方案,但我对解释不是很清楚。我试图清楚地理解如何解决这个问题并在 Java 中实施的逻辑。感谢任何帮助。

更新:这是一道面试题。现在,我正在努力提高我的知识。这对我来说是个有趣的问题。如果我违反任何堆栈规则,我可以删除。

这是我所做的研究: Is there an equivalent of Scala's Either in Java 8?

Algorithm for finding all paths in a NxN grid

http://www.geeksforgeeks.org/check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not/

import java.util.Scanner;

public class Run{
    public static void main(String []args){
        int angle = 0, c = 0;
        int[] coords = {0,0};
        String d;
        Scanner in = new Scanner(System.in);
        System.out.println("Input your command");
        d = in.nextLine();
        for (c = 0; c < d.length; c++){
            if (d[c] == 'R'){
                 angle = (angle + 90)%360;
            }else if (d[c] == 'L'){
                 angle = (angle + 270)%360;
            }else if (d[c] == 'F'){
                 switch(angle){
                      case 0: coords[1]++;break;
                      case 90: coords[0]++;break;
                      case 180: coords[1]--;break;
                      case 270: coords[0]--;
                }
            }
         }
         System.out.println('['+coords[0]+','+coords[1]+']');
    }
}

我觉得这段代码够简单了。 目前我没有Java环境,所以无法测试。如果我错了请纠正我

我已经为你准备了以下代码:

public static String calculate(String str) {
    int x = 0;
    int y = 0;
    int[][] move = {{0,1}, {1,0}, {-1,0}, {0,-1}};
    int dir = 0;

    for (char ch: str.toCharArray()) {
        if (ch == 'F') { 
            x += move[dir][0]; 
            y += move[dir][1]; 
        } else if (ch == 'L') {
            dir++;
        } else if (ch == 'R') {
            dir--;
        }
        dir = (dir + 4) % 4;
    }
 return "[" + x + ", " + y + "]";
 }

让我们分析一下我天真的解决方案。

  • int[][] move = {{0,1}, {1,0}, {-1,0}, {0,-1}}; 是当你向左旋转时移动的所有组合 led 变量 dir.
  • 循环String str得到每个命令
  • 读取命令,如果是F,则向dir方向移动。子数组为轴。
  • 在旋转的情况下,添加或减去 dir 以获得正确的结果。
  • 最终使 dir 不与 dir = (dir + 4) % 4; 溢出。这意味着当我向下移动 dir = 0 并向左移动 (dir--) 时,它会导致 dir=-1,这是非法的。所以dir + 4 = 33 % 4 = 3,它给出了最后一组方向。

希望对您有所帮助,您现在已经理解其中的逻辑了。

超级酷帅,根据我的看法你的逻辑是正确的,我测试了你的代码,我发现了一些错误,你的 string d 在for循环前需要转换array *

in.nextLine().toCharArray()

*;字符串 d 将是 char[]d 。你的打印输出我也改变了

("["+coords[0]+","+coords[1]+"]")

。这是我的完整代码,我 did.After 它正在工作