WeightedDice

class WeightedDice<T>(weights: Map<T, Double>, random: Random = Random)(source)

A weighted die that produces outcomes with probabilities proportional to their weights.

Weights are normalized internally so they do not need to sum to 1. Uses a cumulative weight lookup with binary search for O(log n) roll time, where n is the number of outcomes.

Example:

val die = WeightedDice(mapOf("A" to 3.0, "B" to 1.0))
die.roll() // "A" with 75% probability, "B" with 25%

Parameters

weights

a map from each outcome to its non-negative finite weight. At least one weight must be positive. The iteration order of the map determines the internal ordering of outcomes; use an insertion-ordered map (e.g. linkedMapOf) for reproducible results with a seeded random.

random

the random number generator. Defaults to Random.

Type Parameters

T

the type of outcomes.

Throws

if any weight is negative, non-finite, or all weights are zero.

Constructors

Link copied to clipboard
constructor(weights: Map<T, Double>, random: Random = Random)

Functions

Link copied to clipboard
fun roll(): T

Rolls the die and returns one outcome, selected with probability proportional to its weight.