Random part chooser with weight

how do i make it so that theres a code that chooses between 1-5, and some numbers have higher and lower probability of being chosen?

like for example the number 1 has to be chosen 2 times for the number 2 to be chosen, like imagie a lucky spinning wheel with 3 segments , and 2 of the segments are number one, and only one segment is the number 2, so it has like a 1:3 probability to be chosen.

1 Like

You can do exactly what you mentioned with the spinning wheel, choose a random number from 1 to whatever and set certain numbers equal to 1 - 5. For example: if i get the number 50 from the random number, I can reference whatever table I have and see 30-50 is 3 so then I use that as my random number.

Make a table. Example:

local chances = {
[20] = 1,
[20] = 2,
[60] = 3}

--Then:
local random = math.random(1,100)
local result
for weighting, value in pairs (chances) do
random -= weighting
if random <= 0 then
result = value
break
end
end```

Something like this should work
1 Like

made an example

local weights = { -- format: number, weight
    [1] = 2,
    [2] = 1,
    [3] = 1,
    [4] = 1,
    [5] = 1
}

local weightedList = {}
for number, weight in pairs(weights) do
    for i = 1, weight do
        table.insert(weightedList, number)
    end
end

local function choose()
    local index = math.random(1, #weightedList)
    return weightedList[index]
end

math.randomseed(os.time())

for i = 1, 10 do -- test
    print(choose())
end
2 Likes

If you want weights that don’t add up to 100, you first make a function which adds all the indexes up then do a math.random (1, sumOfAllIndexes)

Then my example should work. Or your example could work but if your weights are very refined (like 1000 to 1) then the array will be very long.