ProbabilityDistributor
ProbabilityDistributor is a class that allows you pick a random item from a table of weighted items. The given WeightsTable must be in the format of:
{
Weight: Weight;
Value: any;
}
Where Weight
is a number, NumberRange or a function that returns a number or NumberRange, and Value is any value.
The Weights are calculated during object construction. Even if the return value of your functions change, the
weights will not. If you want to take advantage of updated weights, you must create a new ProbabilityDistributor.
If a NumberRange is detected as a weight, it will generate a random INTEGER between the min and max values of
the Range. If you need more granular control over the weights, you can pass a function that returns a number/NumberRange.
[Example]
local WeightTable = {
{Value = "A", Weight = 100};
{Value = "B", Weight = 50};
{Value = "C", Weight = 25};
{Value = "D", Weight = 25};
}
local Distributor: ProbabilityDistributor<string> = ProbabilityDistributor.new(WeightTable)
local randomValue = Distributor:Roll() --// Has a 50% chance of returning "A", 25% chance of returning "B", and so on...
print(randomValue)
Types
Weight
A valid input for the weight of an item in the WeightsTable. Allows for functions to be passed in to generate a weight on the fly. If a NumberRange is given in, it will generate a random INTEGER between the min and max values of the Range.
WeightedItem<T>
The format weights and an associated value must be in.
WeightedArray<T>
A valid input for the WeightsTable.
Functions
new
ProbabilityDistributor.
new
(
randomOrSeed:
(
Random
|
number
)
?
--
An optional random number generator to use for the rolls. If a number is passed, it will be used as the seed for a new random number generator. If nothing is passed, it will create a new Random and use the current time as the seed.
) →
ProbabilityDistributor
<
T
>
--
A new probability distributor of type T. Where T is the type of the value of the weighted item.
Constructs a new ProbabilityDistributor
Roll
ProbabilityDistributor:
Roll
(
luck:
number?
--
[Optional] A number between 0 and 1 that determines how lucky the roll is. The number acts as a chance that it rerolls the item for a better version. 'Better'ness is determined by the initial order of the weights table.
) →
T
--
The value of the item that was rolled.
Rolls the probability distributor for a weighted item.
Clone
ProbabilityDistributor:
Clone
(
) →
ProbabilityDistributor
<
T
>
--
A new probability distributor of type T. Where T is the type of the value of the weighted item.
Clones the probability distributor.
Sample
ProbabilityDistributor:
Sample
(
numOfSamples:
number?
,
--
The number of samples to take. Defaults to 10,000.
luck:
number?
--
The luck to use for the rolls. Defaults to 0.
) →
{
[
T
]
:
number
}
--
A table of the items that were rolled and how many times they were rolled.
Samples the probability distributor to show the distribution of the rolls.