Skip to content

Commit 6d249f0

Browse files
Aseem JainAseem Jain
Aseem Jain
authored and
Aseem Jain
committed
Robot movement program
1 parent 5bdc6bc commit 6d249f0

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

Diff for: src/codechallenge/medium/RobotMovement.java

+97
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package codechallenge.medium;
2+
3+
4+
import java.io.*;
5+
import java.util.*;
6+
import java.text.*;
7+
import java.math.*;
8+
import java.util.regex.*;
9+
10+
/*
11+
Chewy Debug exercise
12+
A robot follows instructions to move around.
13+
14+
It can move in four different directions:
15+
- North
16+
- East
17+
- South
18+
- West
19+
20+
N
21+
|
22+
|
23+
W -------- E
24+
|
25+
|
26+
S
27+
28+
There are three different instructions:
29+
- F will move the robot forward one step, in the direction it's facing
30+
- L will turn the robot counter-clockwise 90 degrees. i.e. if it was facing North, it will now face West
31+
- R will turn the robot clockwise 90 degrees, i.e if it was facing North, it will now face East
32+
33+
We have a buggy implementation of isRoundtrip below. Round trip simply means the robot comes back to where it started after following the instructions.
34+
35+
Our goal here is to
36+
37+
- identify and fix the bugs
38+
- verify the fixes through test cases
39+
*/
40+
41+
public class RobotMovement {
42+
//buggy implementation
43+
//sample instructions are: "FFLF", "RFFRFF", etc
44+
public static boolean isRoundTrip(String instructions) {
45+
int x = 0;
46+
int y = 0;
47+
//possible values : E (0), N (1), W (2), S (3)
48+
int direction = 0;
49+
50+
for (int i = 0; i < instructions.length(); i++) {
51+
switch (instructions.charAt(i)) {
52+
53+
case 'F':
54+
System.out.println(direction);
55+
if (direction == 0) {
56+
x += 1;
57+
} else if (direction == 1 ) {
58+
y += 1;
59+
} else if (direction == 2) {
60+
x -= 1;
61+
} else if (direction == 3) {
62+
y -= 1;
63+
}
64+
System.out.println("movement = "+ x + ":"+y);
65+
break;
66+
67+
case 'L':
68+
direction++;
69+
if ( direction >= 4){
70+
direction = 0;
71+
}
72+
break;
73+
74+
case 'R':
75+
direction = direction - 1;
76+
if (direction < 0) {
77+
direction = 4 - direction;
78+
}
79+
break;
80+
81+
default:
82+
throw new RuntimeException("Unexpected instruction " + instructions.charAt(i));
83+
}
84+
}
85+
System.out.println(x + " : " + y);
86+
// System.out.println(y);
87+
return x == 0 && y == 0;
88+
}
89+
90+
public static void main(String[] args) {
91+
assert 1 != 1 ;
92+
System.out.println( RobotMovement.isRoundTrip("FLFLFLF"));
93+
System.out.println( RobotMovement.isRoundTrip("FRFRFRF"));
94+
System.out.println( RobotMovement.isRoundTrip("RFFRFFFF"));
95+
96+
}
97+
}

0 commit comments

Comments
 (0)