How would i make percentage chances?

Hello there,
how would i make a percentage chance?

For example:

local Chances = {
    ["Basic"] = 75, -- 75 %
    ["Rare"] = 50, -- 50 %
    ["Epic"] = 25, -- 25 %
    ["Legendary"] = 1, -- 1 %
    ["Special"] = 0.5 -- 0.5%
}

Ive heard about math random, like math.random(1, 3) but every chance is like 50%, 50%. For example:

local chance = {
    ["Basic"] = 1,
    ["Legendary"] = 2
   }

math.random(1, 2) -- 1 is 50%, 2 is 50%

-- or

local chance = {
    ["Basic"] = 1,
    ["Legendary"] = 2,
    ["Special"] = 3
   }

math.random(1, 3) -- All 3 are the same chances

1 and 2 and 3 are equalvient to 25%.

But what about 75% for 1?
1% for 2?
0.5% for 3?

However, doing math.random(1, 100) and then checking between with > < would
be very silly and stressful.

I know theres a much easier way.

If yes it would be nice if somebody could help!

1 Like

You can just do this:

local Chances = {
	Basic = 750, -- 75 %
	Rare = 500, -- 50 %
	Epic = 250, -- 25 %
	Legendary = 10, -- 1 %
	Special = 5 -- 0.5%
}

local function RandomFromWeightedTable(OrderedTable)
	local TotalWeight = 0

	for Piece, Weight in pairs(OrderedTable) do
		TotalWeight += Weight
	end

	local Chance = Random.new():NextInteger(1, TotalWeight)

	local Counter = 0

	for Piece, Weight in pairs(OrderedTable) do
		Counter += Weight

		if Chance <= Counter then
			return Piece
		end
	end
end

print(RandomFromWeightedTable(Chances))
9 Likes

Thank you very much

You can also do it by just making a specific number inside a 1000 math.random to work a special function.

local Chances = math.random(1,100)

if Chances == 1 then
print("you got 1 out of 100 chance")
end

Yeah, but if its not 1 i want to always have basic, and percentages.
its like if not chance 1 and if chance 1 and 2 and 3 and 4 and 5 ... and not 1. thats very stressfull,

1 Like

then use else statement to do that.

But in reality I wouldn’t use if statements, I would just use a table. I only did it to be easier for them to read and understand.