假设我有一个类似 1 2 3 4 5
的数组, 我想把它向左旋转 并得到一个新的。
例如,上述数组的 2 次旋转将导致 3 4 5 1 2
.我没有找到任何扩展功能来做到这一点。
最佳答案
您可以在 Array<T>
上编写自己的扩展函数
fun <T> Array<T>.leftShift(d: Int): Array<T> {
val newList = this.copyOf()
var shift = d
if (shift > size) shift %= size
forEachIndexed { index, value ->
val newIndex = (index + (size - shift)) % size
newList[newIndex] = value
}
return newList
}
关于arrays - 旋转 kotlin 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52891684/