public class WeightedTable
extends java.lang.Object
implements java.io.Serializable
ProbabilityTable
solves, though this only looks up an appropriate index
instead of also storing items it can choose; allows positive doubles for weights but does not allow nested tables for
simplicity. This doesn't store an RNG (or RandomnessSource) in this class, and instead expects a long to be given for
each random draw from the table (these long parameters can be random, sequential, or in some other way different
every time). Uses Vose's Alias Method, and is based
fairly-closely on the code given by Keith Schwarz at that link. Because Vose's Alias Method is remarkably fast (O(1)
generation time in use, and O(n) time to construct a WeightedTable instance), this may be useful to consider if you
don't need all the features of ProbabilityTable or if you want deeper control over the random aspects of it.
DiverRNG.determineBounded(long, int)
and DiverRNG.determine(long)
to generate two ints, one used for
probability and treated as a 31-bit integer and the other used to determine the chosen column, which is bounded to an
arbitrary positive int. It does this with just one randomized 64-bit value, allowing the state given to
random(long)
to be just one long.
Constructor and Description |
---|
WeightedTable()
Constructs a useless WeightedTable that always returns the index 0.
|
WeightedTable(double... probabilities)
Constructs a WeightedTable with the given array of weights for each index.
|
Modifier and Type | Method and Description |
---|---|
static WeightedTable |
deserializeFromString(java.lang.String data) |
int |
random(long state)
Gets an index of one of the weights in this WeightedTable, with the choice determined deterministically by the
given long, but higher weights will be returned by more possible inputs than lower weights.
|
java.lang.String |
serializeToString() |
public WeightedTable()
public WeightedTable(double... probabilities)
random(long)
.probabilities
- an array or varargs of positive doubles representing the weights for their own indicespublic int random(long state)
weightedTable.random(++state)
, where state is a long, to ensure the inputs change.
This will always return an int between 0 (inclusive) and size
(exclusive).state
- a long that should be different every time; consider calling with ++state
size
- 1, determined by weights and the given statepublic java.lang.String serializeToString()
public static WeightedTable deserializeFromString(java.lang.String data)
Copyright © Eben Howard 2012–2022. All rights reserved.