Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate kotlin array

Tags:

arrays

kotlin

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.

like image 285
Bolek Sergiusz Avatar asked Oct 19 '18 11:10

Bolek Sergiusz


Video Answer


3 Answers

You can use built-in java Collections.rotate method, but you need to convert your array to list firstly:

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

Outputs

3, 4, 5, 1, 2
like image 79
awesoon Avatar answered Oct 21 '22 08:10

awesoon


I interpret "get a new one" to mean that the extension function should return a new array instance, like so (boundary checks omitted, sliceArray is an stdlib function) :

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

Example

arrayOf(1, 2, 3, 4, 5).rotate(1)
    .also { println(it.joinToString()) } // 2, 3, 4, 5, 1
like image 25
David Soroko Avatar answered Oct 21 '22 08:10

David Soroko


Another extension function, by slicing the array in 2 parts left and right and reassembling it to 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)
}

so this:

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

will print

3 4 5 6 7 1 2
like image 34
forpas Avatar answered Oct 21 '22 08:10

forpas