Kotlin List - random() Function



The Kotlin List random() function returns a random element from the list. It does not specify any order or index. It simply randomly picks an element from the list and returns it.

This function is especially useful in games, simulations, or scenarios requiring random sampling. Visit here to get more information about random().

On each code execution, this function returns a random element that does not match the previous result; Sometimes it matches, but most of the time the result will not match the previous result

Syntax

Following is the syntax of the Kotlin list random() function −

fun <T> Iterable<T>.random(random: Random): T

Parameters

This function accepts an optional parameter called 'random', which represents the object used to control randomness.

Return value

This function returns a random element from the list.

Example 1: Return a Random Element

Let's see a basic example of the random() function, which return an element from the list −

fun main(args: Array<String>) {
   val numbers = listOf(2, 3, 4, 6, 7, 10)
   println(numbers.random())
}

Output

The output can be any element from the list −

6

Example 2: Return a Random Color

In the following example, we use the random()function to return any color from the list −

fun main(args: Array<String>) {
   val colors = listOf("Red", "Blue", "Green", "Yellow")
   val randomColor = colors.random()
   println("Random color: $randomColor")
}

Output

Following is the output −

Random color: Blue

Example 3: Using a Custom Random Generator

This is another example of therandom()function. Here, we generate a random number generator with a fixed seed (1234). It makes sure that the sequence of random numbers generated by this Random instance will be predictable and reproducible −

import kotlin.random.Random

fun main(args: Array<String>) {
   val numbers = listOf(10, 20, 30, 40)
   // Custom seed for reproducibility
   val customRandom = Random(1234)
   val randomNumber = numbers.random(customRandom)
   println("Random number: $randomNumber")
}

Output

Following is the output −

Random number: 10
kotlin_lists.htm
Advertisements