To rotate elements in an array in Kotlin, you can use a combination of array slicing and array concatenation to shift elements to the left or right.
In this example,
array
with integer values.sliceArray
method to extract the last element of the array.sliceArray
method again to extract all elements except the last one.fun main() {
val array = arrayOf(1, 2, 3, 4, 5)
val rotatedArray = arrayOf(array.last()) + array.sliceArray(0 until array.size - 1)
println("Original Array: ${array.joinToString()}")
println("Rotated Array: ${rotatedArray.joinToString()}")
}
Original Array: 1, 2, 3, 4, 5 Rotated Array: 5, 1, 2, 3, 4
In this example,
array
with string values.sliceArray
method to extract all elements except the first one.sliceArray
method again to extract the first element of the array.fun main() {
val array = arrayOf("a", "b", "c", "d", "e")
val rotatedArray = array.sliceArray(1 until array.size) + arrayOf(array.first())
println("Original Array: ${array.joinToString()}")
println("Rotated Array: ${rotatedArray.joinToString()}")
}
Original Array: a, b, c, d, e Rotated Array: b, c, d, e, a
In this tutorial, we learned How to Rotate Elements in an Array in Kotlin language with well detailed examples.