weightedRandomOrNull

fun <T> List<T>.weightedRandomOrNull(weights: List<Double>, random: Random = Random.Default): T?

Returns a weighted random element, or null when the arguments are invalid.

Behaves like weightedRandom for valid arguments and returns null instead of throwing when the list is empty, when weights and the list differ in size, when any weight is negative, NaN, or infinite, or when the total weight is not strictly positive.

Parameters

weights

one non-negative finite weight per element of this list.

random

the source of randomness, Random.Default by default.