# How to get a random choice from a table with Chances defined?

## Recommended Posts

So , first of all we have a table from choices available

Quote

choices = {

"First Item", -- index 1

"Second Item", -- index 2

"Third Item", -- index 3

}

what we should do if we wanna make another table that has the 70% Chance to get the "First Item" and 15% Chance for "Second Item" and 15% for "Third Item" ?

• Moderators

Hi. A solution if you give weight to items, so 1 weight = 1% chance.

```local totalWeight = 100 -- SUM of weights

-- IMPORTANT, add items in ascending order by weights
local choices = {
{"Second item", 15},
{"Third item", 15},
{"First item", 70},
}

function getRandomChoice()
local randomWeight = math.random(totalWeight) -- get a random weight (between 1-100)
-- loop trough table, and find which item is at the random weight. (for example, at the 20th position is "Third item")
for i, choice in ipairs(choices) do
if randomWeight <= choice[2] then
return choice[1]
end
randomWeight = randomWeight - choice[2]
end
end```

I hope you understand it, but there is a video, it's C# but maybe helps: https://www.youtube.com/watch?v=OUlxP4rZap0

Edited by Patrick
• 1

Oh , i got that

it's a good idea bro

Thank you for sharing it ♥

• 1

## Create an account

Register a new account