Kotlin Array - shuffle() Function



The Kotlin array shuffle() function is used to randomly shuffle the elements of an array, effectively providing a way to mix up the contents.

This function also uses a random number generator (i.e. seed value) to reorder the elements.

Syntax

Following is the syntax of Kotlin array shuffle() function −

fun <T> Array<T>.shuffle()

Parameters

This function does not accepts any value.

Return value

The function does not return any value; it shuffles the elements of an array in place.

Example 1

The following is a basic example to demonstrate the use of shuffle() function −

fun main(args: Array<String>) {
   val numbers = arrayOf(1, 2, 3, 4, 5)
   
   // Shuffling the array
   numbers.shuffle()
   println("Shuffled array: ${numbers.joinToString(", ")}")
}

Output

The above code generate following output −

Shuffled array: 3, 5, 2, 1, 4

Example 2

Now, Let's see another example, we use shuffle() function to randomly shuffle the elements of an array in place −

fun main(args: Array<String>){
   var arr1 = arrayOf<Int>(1,2,3,4,5)
   arr1.shuffle();
   for ((i,e) in arr1.withIndex()){
      println("$i --> $e")
   }
}

Output

Following is the output −

0 --> 2
1 --> 5
2 --> 1
3 --> 4
4 --> 3

Example 3

The below example uses shuffle() function with seed value of 42 to Shuffling the array with a specific random order −

import kotlin.random.Random

fun main(args: Array<String>) {
   val numbers = arrayOf(1, 2, 3, 4, 5)    
   // Shuffling the array with a specific Random instance
   numbers.shuffle(Random(42))
   println("Shuffled array with seed 42: ${numbers.joinToString(", ")}")
}

Output

Following is the output −

Shuffled array with seed 42: 1, 5, 3, 2, 4
kotlin_arrays.htm
Advertisements