Created
October 19, 2020 08:40
-
-
Save SiAust/23cd38c3c42755c600aaa04f08ff549d to your computer and use it in GitHub Desktop.
Enum example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Move { | |
public static void main(String[] args) { | |
Robot robot = new Robot(0,0, Direction.UP); | |
System.out.printf("robotX: %d robotY: %d\n", robot.getX(), robot.getY()); | |
moveRobot(robot, 10, 0); | |
System.out.printf("robotX: %d robotY: %d\n", robot.getX(), robot.getY()); | |
} | |
public static void moveRobot(Robot robot, int toX, int toY) { | |
while (robot.getX() != toX || robot.getY() != toY) { | |
if (robot.getX() < toX) { | |
while (!robot.getDirection().equals(Direction.RIGHT)) { // move right | |
robot.turnLeft(); | |
} | |
robot.stepForward(); | |
} | |
if (robot.getX() > toX) { | |
while (!robot.getDirection().equals(Direction.LEFT)) { // move left | |
robot.turnLeft(); | |
} | |
robot.stepForward(); | |
} | |
if (robot.getY() < toY) { | |
while (!robot.getDirection().equals(Direction.UP)) { // move up | |
robot.turnLeft(); | |
} | |
robot.stepForward(); | |
} | |
if (robot.getY() > toY) { | |
while (!robot.getDirection().equals(Direction.DOWN)) { // move down | |
robot.turnLeft(); | |
} | |
robot.stepForward(); | |
} | |
} | |
} | |
} | |
//Don't change code below | |
enum Direction { | |
UP(0, 1), | |
DOWN(0, -1), | |
LEFT(-1, 0), | |
RIGHT(1, 0); | |
private final int dx; | |
private final int dy; | |
Direction(int dx, int dy) { | |
this.dx = dx; | |
this.dy = dy; | |
} | |
public Direction turnLeft() { | |
switch (this) { | |
case UP: | |
return LEFT; | |
case DOWN: | |
return RIGHT; | |
case LEFT: | |
return DOWN; | |
case RIGHT: | |
return UP; | |
default: | |
throw new IllegalStateException(); | |
} | |
} | |
public Direction turnRight() { | |
switch (this) { | |
case UP: | |
return RIGHT; | |
case DOWN: | |
return LEFT; | |
case LEFT: | |
return UP; | |
case RIGHT: | |
return DOWN; | |
default: | |
throw new IllegalStateException(); | |
} | |
} | |
public int dx() { | |
return dx; | |
} | |
public int dy() { | |
return dy; | |
} | |
} | |
class Robot { | |
private int x; | |
private int y; | |
private Direction direction; | |
public Robot(int x, int y, Direction direction) { | |
this.x = x; | |
this.y = y; | |
this.direction = direction; | |
} | |
public void turnLeft() { | |
direction = direction.turnLeft(); | |
} | |
public void turnRight() { | |
direction = direction.turnRight(); | |
} | |
public void stepForward() { | |
x += direction.dx(); | |
y += direction.dy(); | |
} | |
public Direction getDirection() { | |
return direction; | |
} | |
public int getX() { | |
return x; | |
} | |
public int getY() { | |
return y; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment