Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. public class Robot {
  2. public static final int N = 1;
  3. public static final int E = 2;
  4. public static final int S = 3;
  5. public static final int W = 4;
  6. private int x = 0;
  7. private int y = 0;
  8. private static int boundaryX = 0;
  9. private static int boundaryY = 0;
  10. private int facing = N;
  11. public Robot() {
  12. }
  13. public static void setBoundary(int x, int y) {
  14. boundaryX = x;
  15. boundaryY = y;
  16. }
  17.  
  18. public void setPosition(int x, int y, int facing) {
  19. this.x = x;
  20. this.y = y;
  21. this.facing = facing;
  22. }
  23. public void printPosition() {
  24. char dir = 'N';
  25. if (facing == 1) {
  26. dir = 'N';
  27. } else if (facing == 2) {
  28. dir = 'E';
  29. } else if (facing == 3) {
  30. dir = 'S';
  31. } else if (facing == 4) {
  32. dir = 'W';
  33. }
  34. System.out.println(x + " " + y + " " + dir);
  35. }
  36. public void process(String commands) {
  37. for (int i = 0; i < commands.length(); i++) {
  38. process(commands.charAt(i));
  39. }
  40. }
  41. private void process(char command) {
  42. if (command == 'L') {
  43. turnLeft();
  44. } else if (command == 'R') {
  45. turnRight();
  46. } else if (command == 'M') {
  47. move();
  48. }
  49. }
  50. private void move() {
  51. if (facing == N) {
  52. this.y++;
  53. if (this.y > boundaryY) {
  54. this.y = boundaryY;
  55. }
  56. } else if (facing == E) {
  57. this.x++;
  58. if (this.x > boundaryX) {
  59. this.x = boundaryX;
  60. }
  61. } else if (facing == S) {
  62. this.y--;
  63. if (this.y < 0) {
  64. this.y = 0;
  65. }
  66. } else if (facing == W) {
  67. this.x--;
  68. if (this.x < 0) {
  69. this.x = 0;
  70. }
  71. }
  72. }
  73. private void turnLeft() {
  74. facing = facing == N ? W : facing - 1;
  75. }
  76. private void turnRight() {
  77. facing = facing == W ? N : facing +1;
  78. }
  79. public static void main(String args[]) {
  80. Robot.setBoundary(5, 5); // sets boundary
  81. Robot robot = new Robot();
  82. robot.setPosition(1, 2, N);
  83. robot.process("LMLMLMLMM");
  84. robot.printPosition(); // prints 1 3 N
  85. robot.setPosition(3, 3, E);
  86. robot.process("MMRMMRMRRM");
  87. robot.printPosition(); // prints 5 1 E
  88. // try to move out of boundary
  89. robot.setPosition(1, 2, N);
  90. robot.process("LMLMLMLMMMMMMMMMMM");
  91. robot.printPosition(); // prints 1 5 N
  92. robot.process("LMLMLMLMMMMMMMMMMMRRMMMMMMMM");
  93. robot.printPosition(); // prints 1 0 S
  94. }
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement