-
-
Save sreereddymenon/ab42be6436ac1416dec9f39732451dfb 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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