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

How do I make a... weighted? math.random?

Asked by 5 years ago
01local Egg = game.Workspace.Eggs.TestEgg.ClickyBrick.Thebrick
02 
03Egg.ClickDetector.MouseClick:connect(function()
04    print ("click from egg was detected") --Prints a message when the part is clicked.
05    local EggValue = math.random(1,4) --Gets a random number for the pet which can be hatched. As EggValue.
06    print ("EggValue") --Prints the number got
07 
08    if EggValue == 1 then
09        print ("You have pet number one.")
10    end
11 
12end)

How do I make 1, 2, and 3 more likely to appear, and 4 rarer?

1 answer

Log in to vote
0
Answered by
gskw 1046 Moderation Voter
5 years ago

You can create a custom function which maps values in the interval from 0 to 1 to 1, 2, 3 and 4. For example, if you wanted the first three to appear with a 30% chance and 4 to appear with a 10% chance, you could use a function like this:

01local function WeightedRandom()
02    local Random = math.random() -- uniformly distributed decimal number from 0 to 1
03    if Random <= 0.3 then
04        return 1 -- 0 to 0.3
05    elseif Random <= 0.6 then
06        return 2 -- 0.3 to 0.6
07    elseif Random <= 0.9 then
08        return 3 -- 0.6 to 0.9
09    else
10        return 4 -- 0.9 to 1
11    end
12end

Please note that math.random is considered deprecated on Roblox. The preferred way to generate random numbers is to use the Random object. [1]

[1]: Roblox DevHub: Random object

0
If ROBLOX hasn't 100% depreciated it, then I wouldn't recommend using it. This is because the new Random could have bugs, which will mean it won't work right. matiss112233 258 — 5y
Ad

Answer this question