Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Pick random value from table with different chances?

Asked by
NiKxzsu 13
5 years ago

Let's say I have a table like this.

local tab = {"a","b","c"}

How do I randomly pick one value from the table but give each value a different chance to be picked? Example: "a" has a 50% chance to be picked, "b" has 30% and "c" has 20%.

1 answer

Log in to vote
1
Answered by
Rare_tendo 3000 Moderation Voter Community Moderator
5 years ago

You're going to have to use math.random. This tutorial will tell you about it.

For a percentage chance of a value, you should get the percentage of the number of values there:

-- Calculate chance from percentage
local a_chance = (50/100)*#tab
local b_chance = a_chance+(30/100)*#tab
local c_chance = b_chance+(20/100)*#tab
local randomNumber = math.random()*3 -- Generate a random number

-- Find the value from 'randomNumber'

if randomNumber >= 0 and randomNumber <= a_chance then
    print('A is chosen')
elseif randomNumber > a_chance and randomNumber <= c_chance then
    print('B is chosen')
else
    print('C is chosen')
end
Ad

Answer this question