Kotlin Array.shuffle()

Kotlin Array.shuffle() function

In Kotlin, the Array.shuffle() function is used to randomly shuffle the elements of an array.

This function modifies the original array in-place, resulting in a new order of elements each time it is called.

This can be useful when you want to randomize the sequence of elements in an array, such as when implementing a card game, quiz questions, or any scenario where a random order is desired.

In this tutorial, we’ll explore the syntax of the Array.shuffle() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the shuffle() function is

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

The Array.shuffle() function does not take any parameters.

The Array.shuffle() function does not return any value.

Examples for Array.shuffle() function

1. Shuffling an Array of Numbers

In this example, we’ll use shuffle() to randomly shuffle the elements of an array of numbers.

Kotlin Program

fun main() {
    val numbersArray = intArrayOf(1, 2, 3, 4, 5)
    println("Original Array\n${numbersArray.contentToString()}")

    // Shuffling the array of numbers
    numbersArray.shuffle()

    // Printing the shuffled array
    println("Shuffled Array\n${numbersArray.contentToString()}")
}

Output

Original Array
[1, 2, 3, 4, 5]
Shuffled Array
[3, 1, 2, 4, 5]

The output could vary due to the random nature of shuffling.

2. Shuffling an Array of Strings

In this example, we’ll use shuffle() to randomly shuffle the elements of an array of strings.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("apple", "banana", "kiwi", "mango")
    println("Original Array\n${wordsArray.contentToString()}")

    // Shuffling the array of strings
    wordsArray.shuffle()

    // Printing the shuffled array
    println("Shuffled Array\n${wordsArray.contentToString()}")
}

Output

Original Array
[apple, banana, kiwi, mango]
Shuffled Array
[banana, kiwi, apple, mango]

The output could vary due to the random nature of shuffling.

Summary

In this tutorial, we’ve covered the Array.shuffle() function in Kotlin arrays, its syntax, and how to use it to randomly shuffle the elements of an array.