我有一个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(_)允许您以编程方式访问枚举的成员。
发布于 2016-12-02 19:32:13
自定义序列,它无限期地重复给定的序列或列表,可以很容易地用flatten编写
fun <T> Sequence<T>.repeatIndefinitely(): Sequence<T> = 
    generateSequence(this) { this }.flatten()
fun <T> List<T>.repeatIndefinitely(): Sequence<T> =
    this.asSequence().repeatIndefinitely()发布于 2016-12-02 21:07:57
您可以在Kotlin中循环列表/集合,方法是生成一个重复返回列表/集合的序列,然后将其扁平化。例如:
generateSequence { listOf("a", "b") }.flatten().take(5).toList()
// [a, b, a, b, a]您可以定义自己的模块函数,将负数和正数强制使用有效的索引来访问列表中的元素(另请参阅Google的IntMath.mod(int, int)):
infix fun Int.modulo(modulus: Int): Int {
    if (modulus <= 0) throw ArithmeticException("modulus $modulus must be > 0")
    val remainder = this % modulus
    return if (remainder >= 0) remainder else remainder + modulus
}
val list = listOf("a", "b", "c", "d")
list[-1 modulo list.size] // last element
list[-2 modulo list.size] // second to last element
list[+9 modulo list.size] // second element
list[-12 modulo list.size] // first elementhttps://stackoverflow.com/questions/40938716
复制相似问题