public class WeightedChoice<T> extends Object
Map
from
items (of type T
) to weights of type Number
, supplied
to the constructor; these weights are normalized internally to act as
probabilities.
This implementation selects items in O(1) time, and requires O(n) space.
Modifier and Type | Field and Description |
---|---|
static double |
DEFAULT_THRESHOLD
The default minimum value that is treated as a valid probability
(as opposed to rounding error from floating-point operations).
|
Constructor and Description |
---|
WeightedChoice(Map<T,? extends Number> item_weights)
Equivalent to
this(item_weights, new Random(), DEFAULT_THRESHOLD) . |
WeightedChoice(Map<T,? extends Number> item_weights,
double threshold)
Equivalent to
this(item_weights, new Random(), threshold) . |
WeightedChoice(Map<T,? extends Number> item_weights,
Random random)
Equivalent to
this(item_weights, random, DEFAULT_THRESHOLD) . |
WeightedChoice(Map<T,? extends Number> item_weights,
Random random,
double threshold)
Creates an instance with the specified mapping from items to weights,
random number generator, and threshold value.
|
Modifier and Type | Method and Description |
---|---|
T |
nextItem()
Retrieves an item with probability proportional to its weight in the
Map provided in the input. |
void |
setRandomSeed(long seed) |
public static final double DEFAULT_THRESHOLD
public WeightedChoice(Map<T,? extends Number> item_weights)
this(item_weights, new Random(), DEFAULT_THRESHOLD)
.item_weights
- a map from items to their weightspublic WeightedChoice(Map<T,? extends Number> item_weights, double threshold)
this(item_weights, new Random(), threshold)
.item_weights
- a map from items to their weightsthreshold
- the minimum value that is treated as a probability
(anything smaller will be considered equivalent to a floating-point rounding error)public WeightedChoice(Map<T,? extends Number> item_weights, Random random)
this(item_weights, random, DEFAULT_THRESHOLD)
.item_weights
- a map from items to their weightsrandom
- the Random instance to use for selectionpublic WeightedChoice(Map<T,? extends Number> item_weights, Random random, double threshold)
The mapping defines the weight for each item to be selected; this will be proportional to the probability of its selection.
The random number generator specifies the mechanism which will be used to provide uniform integer and double values.
The threshold indicates default minimum value that is treated as a valid probability (as opposed to rounding error from floating-point operations).
item_weights
- a map from items to their weightsrandom
- the Random instance to use for selectionthreshold
- the minimum value that is treated as a probability
(anything smaller will be considered equivalent to a floating-point rounding error)public void setRandomSeed(long seed)
seed
- the seed to be used by the internal random number generatorpublic T nextItem()
Map
provided in the input.Copyright © 2015. All rights reserved.