gpt4 book ai didi

arrays - 旋转 kotlin 数组

转载 作者:行者123 更新时间:2023-12-04 16:38:11 25 4
gpt4 key购买 nike

假设我有一个类似 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com