RandomSelector

interface RandomSelector<E>

A generic interface for selecting random elements from a collection, supporting both uniform and weighted selection.

The RandomSelector provides a flexible way to pick elements randomly, either using equal probabilities or custom weights, and supports various collection types including Iterable and Flow.

Example 1: Simple Random Selection

val items = listOf("Apple", "Banana", "Cherry")
val selector = RandomSelector.fromIterable(items)

println(selector.pick()) // Prints a random item from the list

Example 2: Weighted Random Selection

data class Item(val name: String, val weight: Double)
val items = listOf(
Item("Common", 1.0),
Item("Uncommon", 0.5),
Item("Rare", 0.1)
)

val selector = RandomSelector.fromWeightedIterable(items) { it.weight }

println(selector.pick()) // Prints an item with probability proportional to its weight

Example 3: Weighted Random Selection with Enums

enum class Rarity(override val weight: Double) : Weighted {
COMMON(1.0),
UNCOMMON(0.5),
RARE(0.1),
VERY_RARE(0.01)

companion object {
val selector = RandomSelector.fromWeightedIterable(entries)
}
}

for (i in 1..10) {
println(Rarity.selector.pick()) // Prints a random rarity based on its weight
}

Example 4: Infinite Random Flow

val items = listOf("A", "B", "C")
val selector = RandomSelector.fromIterable(items)
val randomFlow = selector.flow()

randomFlow.take(5).collect { println(it) } // Continuously emits random items

Parameters

E

The type of elements to be selected.

Types

Link copied to clipboard
object Companion

Functions

Link copied to clipboard
abstract fun flow(randomGenerator: RandomGenerator = random): Flow<E>

Creates an infinite Flow that emits random elements.

Link copied to clipboard
abstract fun pick(randomGenerator: RandomGenerator = random): E

Picks a single random element from the collection.