Rotate a List in Kotlin
This article explores different ways to rotate a list in Kotlin.
1. Using Collections.rotate() function
To rotate a list by some position, use the built-in static function Collections.rotate(). The following code example shows invocation for this function, where the code left-rotated a list by 2 positions.
|
1 2 3 4 5 6 7 8 9 10 |
import java.util.* fun main() { val values = (1.. 5).toMutableList() val leftShift = 2 Collections.rotate(values, leftShift) println(values) // [4, 5, 1, 2, 3] } |
To right-shift the list, pass the negative position to the Collections.rotate() function. For example, passing -2 will right-rotate a list by 2 positions, as shown below:
|
1 2 3 4 5 6 7 8 9 10 |
import java.util.* fun main() { val values = (1.. 5).toMutableList() val rightShift = 2 Collections.rotate(values, -rightShift) println(values) // [3, 4, 5, 1, 2] } |
2. Using drop() + take() function
Alternatively, you can write your own extension function on MutableList<T>. To left-rotate a list by specified positions, you can use drop() with take() library function. And to right-rotate a list by specified positions, use takeLast() with dropLast() library function.
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> MutableList<T>.rotateLeft(n: Int) = drop(n) + take(n) fun <T> MutableList<T>.rotateRight(n: Int) = takeLast(n) + dropLast(n) fun main() { val values = (1.. 5).toMutableList() val shift = 2 println(values.rotateLeft(shift)) // [3, 4, 5, 1, 2] println(values.rotateRight(shift)) // [4, 5, 1, 2, 3] } |
3. Using Loop
You can write your custom logic for rotating a list. For example, the following code left-shifts elements in the list by specific positions. The code can be easily modified to right-shift a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun <T> rotateLeft(values: MutableList<T>, shift: Int): List<T> { if (values.isEmpty()) { return values } for (i in 0 until shift) { values.add(0, values.removeAt(values.lastIndex)) } return values } fun main() { val values = (1.. 9).toMutableList() val shift = 3 val rotatedList = rotateLeft(values, shift) println(rotatedList) // [7, 8, 9, 1, 2, 3, 4, 5, 6] } |
That’s all about rotating a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)