Shuffle a list in Kotlin
This article explores different ways to shuffle a list in Kotlin.
1. Using shuffle() function
The simplest and fairly efficient solution is to randomize a list is to use the native function shuffle().
|
1 2 3 4 5 6 7 8 9 10 |
fun <T> shuffle(list: MutableList<T>) { list.shuffle() } fun main() { val list: MutableList<Int?> = (0..10).toMutableList(); shuffle(list) println(list) } |
2. Using Fisher–Yates Shuffle Algorithm
Following is an implementation of Fisher–Yates shuffle algorithm, which shuffles the list from the highest index to the lowest index:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import kotlin.random.Random fun <T> shuffle(list: MutableList<T>) { // start from the end of the list for (i in list.size - 1 downTo 1) { // get a random index `j` such that `0 <= j <= i` val j = Random.nextInt(i + 1) // swap element at i'th position in the list with the element at j'th position val temp = list[i] list[i] = list[j] list[j] = temp } } fun main() { val list: MutableList<Int?> = (0..10).toMutableList(); shuffle(list) println(list) } |
The following is an equivalent version of the Fisher-Yates Shuffle algorithm, which shuffles the list from the lowest index to the highest index:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import kotlin.random.Random fun <T> shuffle(list: MutableList<T>) { // start from the beginning of the list for (i in 0 until list.size - 1) { // get a random index `j` such that `i <= j <= n` val j = i + Random.nextInt(list.size - i) // swap element at i'th position in the list with the element at j'th position val temp = list[i] list[i] = list[j] list[j] = temp } } fun main() { val list: MutableList<Int?> = (0..10).toMutableList(); shuffle(list) println(list) } |
That’s all about shuffling 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 :)