My understanding of the weighted chance system may be muddy, but it yields an unexpected value.
How can I fix this?
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```
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.