Kotlin - RobotSimulator Complete

This commit is contained in:
Anthony C 2017-08-02 12:06:32 -04:00
parent f6885e29f4
commit d2abc4180e

View file

@ -0,0 +1,42 @@
class Robot(var gridPosition: GridPosition, var orientation: Orientation) {
constructor(): this(GridPosition(0,0), Orientation.NORTH)
fun advance(): Unit {
gridPosition = when (orientation) {
Orientation.NORTH -> gridPosition.copy(y = gridPosition.y + 1)
Orientation.SOUTH -> gridPosition.copy(y = gridPosition.y - 1)
Orientation.EAST -> gridPosition.copy(x = gridPosition.x + 1)
Orientation.WEST -> gridPosition.copy(x = gridPosition.x - 1)
}
}
fun turnRight(): Unit {
orientation = when (orientation){
Orientation.NORTH -> Orientation.EAST
Orientation.EAST -> Orientation.SOUTH
Orientation.SOUTH -> Orientation.WEST
Orientation.WEST -> Orientation.NORTH
}
}
fun turnLeft(): Unit {
orientation = when (orientation){
Orientation.NORTH -> Orientation.WEST
Orientation.WEST -> Orientation.SOUTH
Orientation.SOUTH -> Orientation.EAST
Orientation.EAST -> Orientation.NORTH
}
}
fun simulate(inpString: String): Unit {
require(inpString.all { (it == 'R') or (it == 'L') or (it == 'A') })
for (i in inpString){
when (i.toUpperCase()){
'R' -> this.turnRight()
'L' -> this.turnLeft()
'A' -> this.advance()
}
}
}
}