我有一个directions列表,当我向右或向左拐时,我想找到下一个方向。下面是我的工作代码:
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)
}directionsInRightTurnOrder列表并无限地(而且懒洋洋地)遍历它,这将是非常简单和容易阅读的。在Clojure中,我可以使用核心/循环来做到这一点(take 5 (cycle ["a" "b"]))
# ("a" "b" "a" "b" "a")- [http://rubyquicktips.com/post/996814716/use-negative-array-indices](http://rubyquicktips.com/post/996814716/use-negative-array-indices)
- [Negative index to Python list](https://stackoverflow.com/questions/11367902/negative-index-to-python-list)
问题:
cycle吗?发布于 2016-12-02 23:33:16
这是cycle
fun <T : Any> cycle(vararg xs: T): Sequence<T> {
var i = 0
return generateSequence { xs[i++ % xs.size] }
}
cycle("a", "b").take(5).toList() // ["a", "b", "a", "b", "a"]下面是实现转身应用程序的方法:
enum class Turn(val step: Int) { L(-1), R(1) }
enum class Direction {
N, E, S, W;
fun turned(turn: Turn): Direction {
val mod: (Int, Int) -> Int = { n, d -> ((n % d) + d) % d }
return values()[mod(values().indexOf(this) + turn.step, values().size)]
}
}听起来modulo就是你要找的--负指数环绕。在Kotlin的stdlib里找不到所以我带了我自己的。
Direction.N
.turned(Turn.R) // E
.turned(Turn.R) // S
.turned(Turn.R) // W
.turned(Turn.R) // N
.turned(Turn.L) // WEnum#values()和Enum#valueOf(_)允许您以编程方式访问枚举的成员。
https://stackoverflow.com/questions/40938716
复制相似问题