To shuffle an array in Kotlin, you can use the shuffle
method from the kotlin.collections
package.
In this example,
arr
with the values 1, 2, 3, 4, and 5.toMutableList
method, which allows us to use the shuffle
method.shuffle
method on the mutable list to randomly shuffle the elements.fun main() {
val arr = arrayOf(1, 2, 3, 4, 5)
val shuffledArr = arr.toMutableList().apply { shuffle() }
println("Shuffled array: $shuffledArr")
}
Shuffled array: [3, 1, 5, 2, 4]
In this example,
arr
with the values "apple", "banana", "cherry", "date", and "elderberry".toMutableList
method, which allows us to use the shuffle
method.shuffle
method on the mutable list to randomly shuffle the elements.fun main() {
val arr = arrayOf("apple", "banana", "cherry", "date", "elderberry")
val shuffledArr = arr.toMutableList().apply { shuffle() }
println("Shuffled array: $shuffledArr")
}
Shuffled array: [cherry, apple, elderberry, banana, date]
In this tutorial, we learned How to Shuffle an Array in Kotlin language with well detailed examples.