移位Kotlin数组

Bol*_*usz 4 kotlin

假设我有一个类似的数组1 2 3 4 5,我想将它向左旋转n并得到一个新的数组。

例如,上述数组的2旋转将导致3 4 5 1 2。我没有找到任何扩展功能来做到这一点。

Dav*_*oko 7

我将“获取新实例解释为扩展函数应该返回一个新实例,如下所示(省略边界检查):

fun <T> Array<T>.rotate(n: Int) = 
    let { sliceArray(n until size) + sliceArray(0 until n) }
Run Code Online (Sandbox Code Playgroud)


for*_*pas 6

另一个扩展函数,通过将数组切成两部分left并将right其重新组装为right + left

fun <T> Array<T>.leftShift(d: Int) {
    val n = d % this.size  // just in case
    if (n == 0) return  // no need to shift

    val left = this.copyOfRange(0, n)
    val right = this.copyOfRange(n, this.size)
    System.arraycopy(right, 0, this, 0, right.size)
    System.arraycopy(left, 0, this, right.size, left.size)
}
Run Code Online (Sandbox Code Playgroud)

所以这:

val a = arrayOf(1, 2, 3, 4, 5, 6, 7)
a.leftShift(2)
a.forEach { print(" " + it) }
Run Code Online (Sandbox Code Playgroud)

将打印

3 4 5 6 7 1 2
Run Code Online (Sandbox Code Playgroud)


awe*_*oon 5

您可以使用内置的java Collections.rotate方法,但需要先将数组转换为list:

val arr = intArrayOf(1, 2, 3, 4, 5)
val list = arr.toList()
Collections.rotate(list, -2)
println(list.toIntArray().joinToString())
Run Code Online (Sandbox Code Playgroud)

产出

3, 4, 5, 1, 2
Run Code Online (Sandbox Code Playgroud)


Tat*_*aki 5

简单的解决方案:

fun <T> Array<T>.rotateLeft(n: Int) = drop(n) + take(n)
fun <T> Array<T>.rotateRight(n: Int) = takeLast(n) + dropLast(n)
Run Code Online (Sandbox Code Playgroud)

限制是n必须小于或等于数组的长度。

或者,您可以Collections.rotate(...)按如下方式使用。

import java.util.Collections

fun <T> Array<T>.rotate(distance: Int) =
    toList().also { // toList() is a deep copy to avoid changing the original array.
        Collections.rotate(it, distance)
    }

fun main() {
    val xs = arrayOf(1, 2, 3, 4, 5)
    val ys = xs.rotate(-2)
    xs.forEach { print("$it ") } // 1 2 3 4 5
    println(ys) // [3, 4, 5, 1, 2]
}
Run Code Online (Sandbox Code Playgroud)