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 4 years ago
local Egg = game.Workspace.Eggs.TestEgg.ClickyBrick.Thebrick

Egg.ClickDetector.MouseClick:connect(function()
    print ("click from egg was detected") --Prints a message when the part is clicked.
    local EggValue = math.random(1,4) --Gets a random number for the pet which can be hatched. As EggValue.
    print ("EggValue") --Prints the number got

    if EggValue == 1 then
        print ("You have pet number one.")
    end

end)

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
4 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:

local function WeightedRandom()
    local Random = math.random() -- uniformly distributed decimal number from 0 to 1
    if Random <= 0.3 then
        return 1 -- 0 to 0.3
    elseif Random <= 0.6 then
        return 2 -- 0.3 to 0.6
    elseif Random <= 0.9 then
        return 3 -- 0.6 to 0.9
    else
        return 4 -- 0.9 to 1
    end
end

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 — 4y
Ad

Answer this question