Skip to content

Instantly share code, notes, and snippets.

@CodyEngel
Created April 18, 2020 16:08
Show Gist options
  • Save CodyEngel/14e26f8fd64582adff08ba9f94abdcbc to your computer and use it in GitHub Desktop.
Save CodyEngel/14e26f8fd64582adff08ba9f94abdcbc to your computer and use it in GitHub Desktop.
Robot Bound In Circle via Leetcode. Beats 100% memory πŸŽ‰ and beats 6.67% on runtime 😭
class Solution {
fun isRobotBounded(instructions: String): Boolean {
val robot = Robot()
repeat(4) {
instructions.forEach { instruction ->
when (instruction) {
'G' -> robot.move()
'R' -> robot.turnRight()
'L' -> robot.turnLeft()
}
}
}
return robot.coordinates.horizontal == 0 && robot.coordinates.vertical == 0
}
}
class Robot {
private var orientation: Orientation = Orientation.N
var coordinates = Pair<Int, Int>(0, 0)
private set
fun move() {
when (orientation) {
Orientation.N -> coordinates = Pair(coordinates.horizontal, coordinates.vertical + 1)
Orientation.S -> coordinates = Pair(coordinates.horizontal, coordinates.vertical - 1)
Orientation.E -> coordinates = Pair(coordinates.horizontal + 1, coordinates.vertical)
Orientation.W -> coordinates = Pair(coordinates.horizontal - 1, coordinates.vertical)
}
}
fun turnRight() {
orientation = orientation.turnRight()
}
fun turnLeft() {
orientation = orientation.turnLeft()
}
}
sealed class Orientation(val degrees: Int) {
object N : Orientation(0)
object S : Orientation(180)
object E : Orientation(90)
object W : Orientation(270)
fun turnRight(): Orientation {
return Orientation.create(degrees + 90)
}
fun turnLeft(): Orientation {
return Orientation.create(degrees - 90)
}
companion object {
fun create(degrees: Int): Orientation {
return when (degrees) {
0, in 360..Int.MAX_VALUE -> Orientation.N
90 -> Orientation.E
180 -> Orientation.S
else -> Orientation.W
}
}
}
}
val Pair<Int, Int>.horizontal: Int
get() = first
val Pair<Int, Int>.vertical: Int
get() = second
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment