Hello, I’m trying to make a random number generator with bias, is there anyway to do this besides my current method?
local Numbers = {1, 1, 1, 1, 1, 2, 2, 3, 3, 3}
local RandomNumberWithBias = Numbers[math.random(1, #Numbers)]
-- 50% chance to get "1"
-- 20% chance to get "2"
-- 30% change to get "3"
I don’t really see this as efficient and i think (and hope) that there is a better way to get RNG with bias.
Hello. Sorry for the late response, but here’s one slightly more efficient way I use for biased tables:
local module = {}
module.__index = module
function module.FormatBiasTable(BiasedTable)
local FormattedBiasedTable = {}
local last = 0
for name,prob in pairs(BiasedTable) do
FormattedBiasedTable[name] = {min=last};
last += prob;
FormattedBiasedTable[name].max = last-1;
end
return FormattedBiasedTable,last-1,BiasedTable
end
function module.next(BiasedTable,Max)
local SelectedNumber = math.random(0,Max)
for name,range in pairs(BiasedTable) do
if SelectedNumber >= range.min and SelectedNumber <= range.max then return name end
end
end
return setmetatable({},module)
Here’s an example of using this:
local RNG = require(script.RNG);
local Data = {
["1"] = 5,
["2"] = 2,
["3"] = 3
}
local formattedData,maximum = RNG.FormatBiasTable(Data)
local example = {}
for i = 1,10 do
table.insert(example,RNG.next(formattedData,maximum)
end
print(example) -- {'2','2','1','3','3','1','1','1','3','3'}