Get Random Elements From Lists
Sometimes we may need to get a number of random elements from lists. To do this, we can use a function to get the indices of these elements first.
The function getIndices
takes two parameters: num
is the number of elements to get, max
is the maximum value of index.
import java.util.concurrent.ThreadLocalRandom
fun getIndices(num: Int, max: Int): Set<Int> {
val results = mutableSetOf<Int>()
while (results.size < num) {
results.add(ThreadLocalRandom.current().nextInt(max))
}
return results
}
The function getRandomElements
in the code below gets the list of selected elements.
fun <T> getRandomElements(list: List<T>, num: Int): List<T> {
val indices = getIndices(Math.min(num, list.size), list.size)
return indices.map { list[it] }
}
We can invoke getRandomElements
as below.
getRandomElements(listOf(1, 2, 3), 2)