Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Robot {
- public static final int N = 1;
- public static final int E = 2;
- public static final int S = 3;
- public static final int W = 4;
- private int x = 0;
- private int y = 0;
- private static int boundaryX = 0;
- private static int boundaryY = 0;
- private int facing = N;
- public Robot() {
- }
- public static void setBoundary(int x, int y) {
- boundaryX = x;
- boundaryY = y;
- }
- public void setPosition(int x, int y, int facing) {
- this.x = x;
- this.y = y;
- this.facing = facing;
- }
- public void printPosition() {
- char dir = 'N';
- if (facing == 1) {
- dir = 'N';
- } else if (facing == 2) {
- dir = 'E';
- } else if (facing == 3) {
- dir = 'S';
- } else if (facing == 4) {
- dir = 'W';
- }
- System.out.println(x + " " + y + " " + dir);
- }
- public void process(String commands) {
- for (int i = 0; i < commands.length(); i++) {
- process(commands.charAt(i));
- }
- }
- private void process(char command) {
- if (command == 'L') {
- turnLeft();
- } else if (command == 'R') {
- turnRight();
- } else if (command == 'M') {
- move();
- }
- }
- private void move() {
- if (facing == N) {
- this.y++;
- if (this.y > boundaryY) {
- this.y = boundaryY;
- }
- } else if (facing == E) {
- this.x++;
- if (this.x > boundaryX) {
- this.x = boundaryX;
- }
- } else if (facing == S) {
- this.y--;
- if (this.y < 0) {
- this.y = 0;
- }
- } else if (facing == W) {
- this.x--;
- if (this.x < 0) {
- this.x = 0;
- }
- }
- }
- private void turnLeft() {
- facing = facing == N ? W : facing - 1;
- }
- private void turnRight() {
- facing = facing == W ? N : facing +1;
- }
- public static void main(String args[]) {
- Robot.setBoundary(5, 5); // sets boundary
- Robot robot = new Robot();
- robot.setPosition(1, 2, N);
- robot.process("LMLMLMLMM");
- robot.printPosition(); // prints 1 3 N
- robot.setPosition(3, 3, E);
- robot.process("MMRMMRMRRM");
- robot.printPosition(); // prints 5 1 E
- // try to move out of boundary
- robot.setPosition(1, 2, N);
- robot.process("LMLMLMLMMMMMMMMMMM");
- robot.printPosition(); // prints 1 5 N
- robot.process("LMLMLMLMMMMMMMMMMMRRMMMMMMMM");
- robot.printPosition(); // prints 1 0 S
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement