randomSample

fun <T> Iterable<T>.randomSample(n: Int, random: Random = Random): List<T>(source)

Draws a random sample of n elements without replacement.

Uses a partial Fisher-Yates shuffle to select n elements in O(n) time. Each element can appear at most once in the result. The collection is materialized to a mutable list internally.

Example:

listOf(1, 2, 3, 4, 5).randomSample(3) // e.g. [4, 1, 5]

Return

a list of n randomly selected elements.

Parameters

n

the number of elements to draw. Must be between 0 and the collection size.

random

the random number generator. Defaults to Random.

Type Parameters

T

the type of elements.