Help with Weighted Chance System

Hey folks,

My understanding of the weighted chance system may be muddy, but it yields an unexpected value.

How can I fix this?

image
image

I am not sure if this is because I have to account for the rarer chances.

-- This is a Module Script, the roll() function is called in a localscript in PlayerGui
local LuckSystem = {}

-- {Rarity, Chance, Color/GUI}
local rarityTable = {
	{"Common", 539}, -- 56.4%
	{"Uncommon", 300}, -- 30%
	{"Rare", 100}, -- 10%
	{"Epic", 50}, -- 5%
	{"Legendary", 10}, -- 1%
	{"Mythical", 1} -- 0.1%
}

function LuckSystem.roll()
	local weight = 0
	for index, value in pairs(rarityTable) do
		weight += rarityTable[index][2]
	end

	local randomNum = math.random(1, weight)
	weight = 0

	for index, value in pairs(rarityTable) do
		weight += rarityTable[index][2]

		if weight >= randomNum then
			return rarityTable[index][1]..":"..randomNum
		end
	end
end

return LuckSystem```

Use ipairs, using pairs wont iterate through the array in order.

1 Like

pairs does in fact loop through arrays in order. I think you are mistaking it for a dictionary, which is iterated in arbitrary order.

1 Like

As far as I can tell this is about what one should expect on output.

You got the value “rare” when the picked number was 896. That’s even between the value 839 which is what separates rare from uncommon and 939 which is what separates from rare from epic.

I’m assuming the green 10.4% is the output for testing how frequently rare turned up. Though not 10% there is always going to be a bit of variance from the theoretical output due to random chance. You’re within half a % if my assumptions are correct which implies it is doing what you think it is.

1 Like

Ah, just to clarify – the 10.4% was displayed as rare because the Epic, Legendary, and Mythical chances were added on top?

In theory, the chances are correct, but the actual percentage shown is invalid (calculated using RNG/10)?