-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRover.java
84 lines (78 loc) · 1.57 KB
/
Rover.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Rover{
int roverPosition(int n, int ncmd, List<String> cmd) {
// i and j represents row and column respectively
int i=0,j=0;
for(int count=0;count<ncmd;count++)
{
if(cmd.get(count).equals("UP")) //if command UP minus the row
{
if((i-1)<0)
{
continue;
}
else
{
i=i-1;
}
}
else if(cmd.get(count).equals("DOWN")) //if command DOWN add the row
{
if((i+1)==n)
{
continue;
}
else
{
i=i+1;
}
}
if(cmd.get(count).equals("LEFT")) //if command LEFT minus the column
{
if((j-1)<0)
{
continue;
}
else
{
j=j-1;
}
}
else if(cmd.get(count).equals("RIGHT")) //if command RIGHT add the column
{
if((j+1)==n)
{
continue;
}
else
{
j=j+1;
}
}
}
return((i*n)+j); //as per the formula given in problem statement
}
public static void main(String[] args) {
List<String> cmd=new ArrayList<String>(); //to store the commands
Scanner s=new Scanner(System.in);
int n;
int ncmd;
String str;
System.out.println("Enter the size of matrix=");
n=s.nextInt();
System.out.println("Enter how many commands do u have=");
ncmd=s.nextInt();
System.out.println("Enter Commands=");
for(int i=0;i<ncmd;i++)
{
str=s.next();
cmd.add(str);
}
Rover r=new Rover();
int pos=r.roverPosition(n, ncmd, cmd);
System.out.println(pos);
s.close();
}
}