I am working on one program, I have to find the position of a robot in a grid, it can move in forward direction and can change its facing towards north, south, east and west and have been provided with a given command sequence. So, what will be the final position of the robot. Use of any type of condition branching (e.g. if/else,switch/case) is prohibited.
Example-
Grid-(100*500)
Robot's initial Position-(5,3)
Possible commands-
N-North,
E-East,
W-West,
S-South,
M-Move forward
Sample Input-{N,S,M.M,E,W,E,S,M,S,M}
I tried using Enum, but the problem I am facing is how to call Enum methods with dynamic values which I am getting using commands.
public class RobotMovesInGrid {
Scanner input = new Scanner(System.in);
String command=input.next();
int commLength = command.length();
static enum Command {
N{@Override public void execute(String g, String r){ System.out.println("do the N move here"); }},
E{@Override public void execute(String g, String r){ System.out.println("do the E move here"); }},
S{@Override public void execute(String g, String r){ System.out.println("do the S move here"); }},
W{@Override public void execute(String g, String r){ System.out.println("do the W move here"); }},
M{@Override public void execute(String g, String r){ System.out.println("do the M move here"); }};
public abstract void execute(String g, String r);
}
public void nextPosition() {
Command c1;
for(int i=0;i<commLength;i++) {
if (command.charAt(i)=='N'||command.charAt(i)=='E'|| command.charAt(i)=='S'|| command.charAt(i)=='W'||command.charAt(i)=='M')
c1= Command.M;// Here instead of M, I am trying to give dynamic commands but it is not taking it
System.out.println("Current position is"+c1);
}
}
}
Could someone please suggest me how to call the Enum methods using commands given as input.