Weighted Selection

Hello! so I made this weighted selection based on a forum post
local Items = {
{“Test1”,1},
{“Test2”,5},
{“Test3”,10},
}
local TotalWeight = 0

for _,ItemData in pairs(Items) do
TotalWeight = TotalWeight + ItemData[2]
end

local function chooseRandomItem()
local Chance = math.random(1,TotalWeight)
local Counter = 0
for _,ItemData in pairs(Items) do
Counter = Counter + ItemData[2]
if Chance <= Counter then
return ItemData[1]
end
end
end

for i=1,10 do
print(chooseRandomItem())
end

and I wanted to make I work with decimal numbers, could anyone help me ?

1 Like

I think one way would be one way to do it.

local Chance = math.random() * TotalWeight

Be sure to test this and make sure the distribution still looks good. I’m not a statistics pro.