Skip to content

Instantly share code, notes, and snippets.

@cloudbank
Last active September 8, 2019 23:34
Show Gist options
  • Save cloudbank/e82cf9aaffdb8f7d7e7fbf9914cbf3b5 to your computer and use it in GitHub Desktop.
Save cloudbank/e82cf9aaffdb8f7d7e7fbf9914cbf3b5 to your computer and use it in GitHub Desktop.
Mars rover given a list of String cmds in an nxn matrix, return the square you end on.
public class Rover {
public static int roverMove(int matrixSize, List<String> cmds) {
int result = 0;
for (int i = 0; i < cmds.size(); i++) {
result = process(cmds.get(i), matrixSize, result);
}
return result;
}
static int process(String cmd, int n, int current) {
if (cmd.equals("DOWN")) {
if (current < (n * n) - n) {
current += n;
}
} else if (cmd.equals("UP")) {
if (current >= n) {
current -= n;
}
} else if (cmd.equals("RIGHT")) {
if (((current + 1) % n) != 0) {
current = current + 1;
}
} else if (cmd.equals("LEFT")) {
if (current % n != 0) {
current = current - 1;
}
}
return current;
}
public static void main(String[] args) {
List l = new ArrayList();
l.add("RIGHT");
l.add("RIGHT");
l.add("DOWN");
roverMove(4, l);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment