Weighted random chance

How would I make a random room picker, that also has different rarities?
Every room has a Rarity IntValue

I already tried doing this from this post:

local chance = math.random(1,totalWeight)
local counter = 0
local randomRoom
for _,room in pairs(rooms:GetChildren()) do
    counter = counter + room.Rarity.Value
    if chance <= counter then
    	randomRoom = room:Clone()

The totalWeight from 10 different rooms is 77

This does not seem to work, as it only selects the room with Rarity 1 every time

How could I fix this?

1 Like

You’re system is a bit odd in that it pre-defines the totalWeight instead of doing that in the function. You’re also trying to use chance <= counter to find whether or not to choose the room, and that isn’t totally random. I’ve set up one that defines the totalWeight in the loop itself, perhaps it could help you a bit?

local pool = {}
for _,room in pairs(rooms:GetChildren()) do
	for i = 1,room.Rarity.Value do
		table.insert(pool,room) -- Define weights
if #pool > 0 then
	local id = math.random(#pool) -- Get a random value
	local randomRoom = pool[id]:Clone() -- Assign value to table
pool = {} -- Clear the table

Wouldnt that just pick a random room instead of a weighted random room?

EDIT: Nevermind, I see now

Thanks! I didnt think about adding the same room to the table multiple times for a bigger chance of appearing, but it totally makes sense!