Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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

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

1 comment

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.