Kotlin Array.random() Tutorial
In Kotlin, the Array.random()
function is used to retrieve a random element from the given array. This function provides a convenient way to select a random item without the need for manually generating random indices or using external libraries.
This tutorial will explore the syntax of the random()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.random()
function is as follows:
fun <T> Array<out T>.random(): T
Examples for Array.random() function
1. Using random() with Array of integers
In this example, we’ll use the random()
function with an Array of integers numbersArray
to select a random integer from the array.
Kotlin Program
fun main() {
val numbersArray = arrayOf(10, 20, 30, 40, 50)
// Using random() to get a random element from the array
val randomElement = numbersArray.random()
// Printing the original array and the random element
println("Numbers Array:\n${numbersArray.contentToString()}\n")
println("Random Element:\n$randomElement")
}
Output
Numbers Array:
[10, 20, 30, 40, 50]
Random Element:
40
The output you got may differ from the one shown above, because of the randomness of the element choosing.
You may run the random command any number of times, and each time a random number is picked from the given array. Like the experiment of throwing a dice, where the array has numbers for 1 to 6.
2. Using random() with String Array
In this example, we’ll use the random()
function with an Array of strings to select a random string from the array.
Kotlin Program
fun main() {
val wordsArray = arrayOf("apple", "banana", "orange", "grape", "kiwi")
// Using random() to get a random element from the array
val randomWord = wordsArray.random()
// Printing the original array and the random word
println("Words Array:\n${wordsArray.contentToString()}\n")
println("Random Word:\n$randomWord")
}
Output
Words Array:
[apple, banana, orange, grape, kiwi]
Random Word:
orange
3. Using random() in a For Loop
In this example, we’ll use the random()
function in a For loop to pick an element randomly from the given array, for n
number of times.
Kotlin Program
fun main() {
val wordsArray = arrayOf("apple", "banana", "orange", "grape", "kiwi")
val n = 10
for(i in 1..n) {
// Using random() to get a random element from the array
val randomWord = wordsArray.random()
println("Random Word: $randomWord")
}
}
Output
Random Word: apple
Random Word: orange
Random Word: orange
Random Word: banana
Random Word: grape
Random Word: apple
Random Word: kiwi
Random Word: banana
Random Word: apple
Random Word: grape
Summary
In this tutorial, we’ve covered the random()
function in Kotlin arrays, its syntax, and how to use it to obtain a random element from an array. This function simplifies the process of selecting random elements without additional complexity. Keep in mind that each call to random()
may result in a different random element.