RandomUtils
Utility functions involving random variables. This is quite useful for a variety of game mechanics.
tip
Each method generally takes a random object in as the last argument, which can be used to seed the randomness. This is especially useful for reproducting state in testing.
Functions
choice
Picks an option from a list. Returns nil if the list is empty.
local options = Players:GetPlayers()
local choice = RandomUtils.choice(options)
print(choice)
Deterministic version:
local options = { "apples", "oranges", "bananas" }
local random = Random.new()
print(RandomUtils.choice(options, random)) --> "apples"
shuffledCopy
RandomUtils.
shuffledCopy
(
list:
{
T
}
,
--
A new table to copy
) →
{
T
}
Creates a copy of the table, but shuffled using fisher-yates shuffle
local options = { "apples", "oranges", "bananas" }
local random = Random.new()
print(RandomUtils.shuffledCopy(options)) --> shuffled copy of table
print(RandomUtils.shuffledCopy(options, random)) --> deterministic shuffled copy of table
shuffle
Shuffles the list in place using fisher-yates shuffle.
local options = { "apples", "oranges", "bananas" }
local random = Random.new()
RandomUtils.shuffle(options, random)
print(options) --> deterministic shuffled copy of table
RandomUtils.shuffle(options)
print(options) --> shuffled table
weightedChoice
RandomUtils.
weightedChoice
(
list:
{
T
}
,
--
List of options
weights:
{
number
}
,
--
Array the same length with weights.
) →
T?
--
May return nil if the list is empty
Like RandomUtils.choice but weighted options in a performance friendly way. Takes O(n) time.
warning
A weight of 0 may still be picked, and negative weights may result in undefined behavior.
local weights = { 1, 3, 10 }
local options = { "a", "b", "c" }
print(RandomUtils.weightedChoice(options, weights)) --> "c"
gaussianRandom
Computes the gaussian random function which is the independent probability curve.