|
| 1 | +package strings.circularMoves; |
| 2 | + |
| 3 | +import utils.InputReader; |
| 4 | + |
| 5 | +public class CircularMoves { |
| 6 | + |
| 7 | + static int x = 0; |
| 8 | + static int y = 0; |
| 9 | + static Direction direction = Direction.N; // start looking at north |
| 10 | + |
| 11 | + public static void main(String[] args) { |
| 12 | + // input |
| 13 | + System.out.print("Print set of moves: M for same direction, L for left, R for right: "); |
| 14 | + String moves = InputReader.readLine(); |
| 15 | + |
| 16 | + // validate input |
| 17 | + if (!moves.matches("^[LMR]*$\n")) { |
| 18 | + System.err.println("Invalid input"); |
| 19 | + } |
| 20 | + |
| 21 | + // check |
| 22 | + if (isCircular(moves.toUpperCase().trim())) { |
| 23 | + System.out.println("Set of moves " + moves + " is circular"); |
| 24 | + } else { |
| 25 | + System.out.println("Set of moves " + moves + " is NOT circular"); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + // start at 0,0, facing UP |
| 30 | + private static boolean isCircular(String moves) { |
| 31 | + for (char c : moves.toCharArray()) { |
| 32 | + switch (c) { |
| 33 | + case 'L': |
| 34 | +// System.out.println("going Left"); |
| 35 | + if (direction.equals(Direction.N)) { |
| 36 | + direction = Direction.W; |
| 37 | + } else if (direction.equals(Direction.W)) { |
| 38 | + direction = Direction.S; |
| 39 | + } else if (direction.equals(Direction.S)) { |
| 40 | + direction = Direction.E; |
| 41 | + } else if (direction.equals(Direction.E)) { |
| 42 | + direction = Direction.N; |
| 43 | + } |
| 44 | + break; |
| 45 | + case 'R': |
| 46 | +// System.out.println("going right"); |
| 47 | + if (direction.equals(Direction.N)) { |
| 48 | + direction = Direction.E; |
| 49 | + } else if (direction.equals(Direction.E)) { |
| 50 | + direction = Direction.S; |
| 51 | + } else if (direction.equals(Direction.S)) { |
| 52 | + direction = Direction.W; |
| 53 | + } else if (direction.equals(Direction.W)) { |
| 54 | + direction = Direction.N; |
| 55 | + } |
| 56 | + break; |
| 57 | + case 'M': |
| 58 | +// System.out.println("going forward"); |
| 59 | + if (direction.equals(Direction.N)) { |
| 60 | + y++; |
| 61 | + } else if (direction.equals(Direction.S)) { |
| 62 | + y--; |
| 63 | + } else if (direction.equals(Direction.E)) { |
| 64 | + x++; |
| 65 | + } else if (direction.equals(Direction.W)) { |
| 66 | + x--; |
| 67 | + } |
| 68 | + break; |
| 69 | + default: // will never reach here |
| 70 | + System.err.println("Invalid set of moves"); |
| 71 | + } |
| 72 | + } |
| 73 | + return (x == 0 && y == 0); // if eventually we're back at 0,0, it is circular |
| 74 | + } |
| 75 | + |
| 76 | + private enum Direction { |
| 77 | + N, E, S, W; |
| 78 | + } |
| 79 | +} |
0 commit comments