☞ Find the final position of robot on 2-D array after executing following commands UP, DOWN, LEFT and RIGHT. The robot starting position is at (0,0).
Sample Input
ulrrdll
Sample Output
(-1,0)
SOURCE CODE
import java.io.*;
import java.util.*;
class RobotPosition{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
String directions;
int i,left=0,right=0,up=0,down=0;
directions = in.nextLine();
for(i = 0;i<directions.length();i++){
switch(directions.charAt(i)){
case 'u':
case 'U':
up++;
break;
case 'd':
case 'D':
down++;
break;
case 'l':
case 'L':
left++;
break;
case 'r':
case 'R':
right++;
break;
}
}
System.out.println("Final position of robot: ("+(right-left)+","+(up-down)+").");
}
}
Sample Input
ulrrdll
Sample Output
(-1,0)
SOURCE CODE
import java.io.*;
import java.util.*;
class RobotPosition{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
String directions;
int i,left=0,right=0,up=0,down=0;
directions = in.nextLine();
for(i = 0;i<directions.length();i++){
switch(directions.charAt(i)){
case 'u':
case 'U':
up++;
break;
case 'd':
case 'D':
down++;
break;
case 'l':
case 'L':
left++;
break;
case 'r':
case 'R':
right++;
break;
}
}
System.out.println("Final position of robot: ("+(right-left)+","+(up-down)+").");
}
}