make Coordinates immutable
This commit is contained in:
parent
b0e6fc197f
commit
9bac80db8e
|
@ -14,8 +14,8 @@ import java.util.logging.Logger;
|
|||
* 3 3-1 3-2 3-3
|
||||
*/
|
||||
public class Coordinates {
|
||||
private int latitude;
|
||||
private int longitude;
|
||||
private final int latitude;
|
||||
private final int longitude;
|
||||
private final Logger logger = Logger.getLogger(Coordinates.class.getName());
|
||||
|
||||
public static Coordinates of(int latitude, int longitude) {
|
||||
|
@ -27,16 +27,19 @@ public class Coordinates {
|
|||
this.longitude = longitude;
|
||||
}
|
||||
|
||||
public Coordinates updatePositionTowards(Direction direction) {
|
||||
public Coordinates getNextPositionTowards(Direction direction) {
|
||||
var newLatitude = latitude;
|
||||
var newLongitude = longitude;
|
||||
switch (direction) {
|
||||
case NORTH -> latitude--;
|
||||
case SOUTH -> latitude++;
|
||||
case WEST -> longitude--;
|
||||
case EAST -> longitude++;
|
||||
case NORTH -> newLatitude--;
|
||||
case SOUTH -> newLatitude++;
|
||||
case WEST -> newLongitude--;
|
||||
case EAST -> newLongitude++;
|
||||
}
|
||||
logger.info(String.format("Updated coordinates towards %s, now is %d-%d",
|
||||
direction, latitude, longitude));
|
||||
return this;
|
||||
direction, newLatitude, newLongitude));
|
||||
|
||||
return new Coordinates(newLatitude, newLongitude);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -58,7 +61,4 @@ public class Coordinates {
|
|||
'}';
|
||||
}
|
||||
|
||||
public Coordinates copy() {
|
||||
return new Coordinates(latitude, longitude);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@ package cat.hack3.codingtests.marsrover;
|
|||
|
||||
public class MarsRover {
|
||||
private final MarsMap marsMap;
|
||||
private final Coordinates currentCoordinates;
|
||||
private Coordinates currentCoordinates;
|
||||
private Direction currentDirection;
|
||||
|
||||
public MarsRover(MarsMap marsMap, Coordinates startingCoordinates, Direction startingDirection) {
|
||||
|
@ -12,11 +12,11 @@ public class MarsRover {
|
|||
}
|
||||
|
||||
public Coordinates moveForward() {
|
||||
return currentCoordinates.updatePositionTowards(currentDirection);
|
||||
return currentCoordinates = currentCoordinates.getNextPositionTowards(currentDirection);
|
||||
}
|
||||
|
||||
public Coordinates moveBackwards() {
|
||||
return currentCoordinates.updatePositionTowards(currentDirection.reversed());
|
||||
return currentCoordinates = currentCoordinates.getNextPositionTowards(currentDirection.reversed());
|
||||
}
|
||||
|
||||
public Direction turnLeft() {
|
||||
|
@ -25,7 +25,7 @@ public class MarsRover {
|
|||
}
|
||||
|
||||
public Coordinates getCurrentCoordinates() {
|
||||
return currentCoordinates.copy();
|
||||
return currentCoordinates;
|
||||
}
|
||||
|
||||
public Direction getCurrentDirection() {
|
||||
|
|
Loading…
Reference in New Issue