I have a list of directions
and want to find the next direction when I take a right or left turn. Here is the working code I have:
enum class Turn { R, L }
enum class Direction { N, E, S, W }
val directionsInRightTurnOrder = listOf(Direction.N, Direction.E, Direction.S, Direction.W)
private fun calculateNextHeading(heading: Direction, turn: Turn): Direction {
val currentIndex = directionsInRightTurnOrder.indexOf(heading)
var nextIndex = currentIndex + if (turn == Turn.R) 1 else -1
if (nextIndex >= directionsInRightTurnOrder.size)
nextIndex = directionsInRightTurnOrder.size - nextIndex
if (nextIndex < 0)
nextIndex += directionsInRightTurnOrder.size
return directionsInRightTurnOrder.get(nextIndex)
}
- However, this would be so much simpler and easier to read if I could take the
directionsInRightTurnOrder
list and cycle through it infinitely (and lazily). In Clojure, I can do that, using clojure.core/cycle:
(take 5 (cycle ["a" "b"]))
# ("a" "b" "a" "b" "a")
Another thing that would help is if I could look up in a list using a negative index, like in Ruby or Python:
Question:
- Can I do
cycle
through a list/collection in Kotlin? - Is there an idiomatic way to do a negative-index-lookup in Kotlin?