Assume that I have an array like 1 2 3 4 5
, I want to rotate it to the left by n and get a new one.
For example the 2 rotation of the above array will result in 3 4 5 1 2
. I didn't found any extension function to do that.
Assume that I have an array like 1 2 3 4 5
, I want to rotate it to the left by n and get a new one.
For example the 2 rotation of the above array will result in 3 4 5 1 2
. I didn't found any extension function to do that.
您可以在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
}