Log in to vote

Percentage-based Probability Selection?

Asked by
Dummiez 360 Moderation Voter
7 years ago

How would you go about doing this in lua? To make it simple, this is an example of a random player selection.

local p = game.Players:GetPlayers()
local rnd = math.random(1,#p)

print (p[rnd].Name) 

How can I make a percentage based for each player but as an array? For example, Dave has 15% chance of being selected, Steve has 65% chance of being selected, Bert has 20% chance of being selected.

My run at it:

local percent = {0.15, 0.65,0.2}
local player = {"Dave", "Steve", "Bert"}
local select

local total = 0
for i = 1, #percent do
    total = total + percent[i]

local rnd = math.random(1,100)/100
for j = 1, #percent do
local prev = percent[j-1] or 0
    if prev >= rnd and rnd <= percent[j] then
    select = player[j]

EDIT: Modified code above, doesn't work accordingly :P

1 answer

Log in to vote
Answered by
BlueTaslem 18044 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago
Edited by User#24403 2 years ago

math.random() (with no parameters) generates any number in the range [0,1).

To select among weighted events, you compute a random value from 0 to the sum of the weights:

local totalweight = 0;
for _, v in ipairs(percent) do
    totalweight = totalweight + v;
local at = math.random() * totalweight;

(Depending on how you generate your percent you could possibly skip this calculation step, if, for instance, you know it will always add up to one)

We then look at our list and can think of it as a numberline. Each item 'owns' a portion of the line from 0 to totalweight, and at is some random place in between. To find which place, we can do something like this:

local where = 0;
for i, v in ipairs(percent) do
    if at < v then
        where = i;
    at = at - v;

Then, where is the corresponding chosen index from percent.

right now this post has 0 upvotes, kinda new, I still don't understand how this works, can you explain more? greatneil80 2472 — 2y

Answer this question