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

Percentage-based Probability Selection?

Asked by
Dummiez 360 Moderation Voter
10 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]
end

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

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

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago
Edited by User#24403 4 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;
end
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;
        break;
    end
    at = at - v;
end

Then, where is the corresponding chosen index from percent.

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

Answer this question