1
0
Fork 0

turn left successfully

This commit is contained in:
Xavier Fontanet 2024-06-20 18:01:08 +02:00
parent 5f44eb39fc
commit 24bc0f8057
3 changed files with 41 additions and 4 deletions

View File

@ -1,6 +1,9 @@
package cat.hack3.codingtests.marsrover;
import static cat.hack3.codingtests.marsrover.MarsMap.Direction.*;
public class MarsMap {
public enum Direction {NORTH, SOUTH, EAST, WEST}
private final int width;
private final int height;
@ -9,5 +12,12 @@ public class MarsMap {
this.height = height;
}
public enum Direction {NORTH, SOUTH, EAST, WEST}
public Direction changeDirectionToLeft(Direction currentDirection) {
return switch (currentDirection) {
case NORTH -> WEST;
case SOUTH -> EAST;
case EAST -> NORTH;
case WEST -> SOUTH;
};
}
}

View File

@ -20,7 +20,16 @@ public class MarsRover {
};
}
public MarsMap.Direction turnLeft() {
currentDirection = marsMap.changeDirectionToLeft(currentDirection);
return currentDirection;
}
public Coordinates getCurrentCoordinates() {
return currentCoordinates;
}
public MarsMap.Direction getCurrentDirection() {
return currentDirection;
}
}

View File

@ -3,9 +3,11 @@ package cat.hack3.codingtests.marsrover;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.function.IntConsumer;
import java.util.stream.IntStream;
import static cat.hack3.codingtests.marsrover.MarsMap.Direction.SOUTH;
import static cat.hack3.codingtests.marsrover.MarsMap.Direction;
import static cat.hack3.codingtests.marsrover.MarsMap.Direction.*;
import static org.testng.Assert.assertEquals;
public class MarsRoverTest {
@ -29,12 +31,28 @@ public class MarsRoverTest {
public void roverMakeItsFirstStep() {
Coordinates currentPosition = rover.moveForward();
assertEquals(currentPosition, Coordinates.of(3, 3));
assertEquals(rover.getCurrentDirection(), SOUTH);
}
@Test
public void make5StepsInARow() {
IntStream.rangeClosed(0, 5)
.forEach(i -> rover.moveForward());
repeatAction(5, i -> rover.moveForward());
assertEquals(rover.getCurrentCoordinates(), Coordinates.of(8, 3));
assertEquals(rover.getCurrentDirection(), SOUTH);
}
@Test
public void turnLef() {
Direction currentDirection = rover.turnLeft();
assertEquals(currentDirection, EAST);
assertEquals(rover.turnLeft(), NORTH);
assertEquals(rover.turnLeft(), WEST);
repeatAction(2, i -> rover.turnLeft());
assertEquals(currentDirection, EAST);
}
private void repeatAction(int times, IntConsumer actionToRepeat) {
IntStream.rangeClosed(0, times)
.forEach(actionToRepeat);
}
}