Create RNG with bias?

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.

1 Like

You could generate a number between 1,100 and see where it is

local num = math.random(1,100)

if num <= 50 then
--50% chance
elseif num > 50 and num <=80 then
--30% CHance
etc....
2 Likes

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'}

Hope this helps! :grinning_face_with_smiling_eyes:

3 Likes