# Using percentages with math.random()

Currently got this

``````local AllDucks = Ducks['Tier ' .. GiftStats[Item].Tier]:GetChildren() -- Gets the 5 items they can win
local WonItem = AllDucks[math.random(1, #AllDucks)] -- Picks the random one
``````

However, each item has it’s own percentage of getting said item.
Common - Percentage = 75
Uncommon - Percentage = 60
Rare - Percentage = 30
Epic - Percentage = 25
Legendary - Percentage = 10

I know they don’t add up to 100. The idea is that all 5 numbers would add up (200) and then the percentages would kinda work from there, so Common would be 75/200 (easier than just doing 37.5/100)

So how can I accomodate these percentages into a math.random?

if I’m understanding correctly?

``````local function getPercentage(num1, num2)
return num1*2/(num2*2)/200;
end
``````

not exactly sure what you want since this is kinda an xy problem

Basically what I want is instead of doing math.random(1, ya da ya da), as that will just get the 5 items and they all have a 20% change of getting picked. I want it so each item has a set percentage.

So Common would have a 75/200 chance, Uncommon a 60/200 chance, etc. etc.

Here, I used this before when I was making a pet system. I hope it helps! (I’ll make a table just for an example)

``````local Pets = {
rarities = {0.6,0.4};
pets = {
{
name="Part";
rarity="Legendary";
};
{
name="Part2";
rarity="Legendary";
};
};
};

local totalweight = 0

for _,v in ipairs(Pets.rarities) do
totalweight = totalweight + v
end

local at = math.random() * totalweight

for i,v in pairs(Pets.rarities) do
if at < v then
print(Pets.pets[i] .. " has been chosen!")
break
end
at = at - v
end
``````
3 Likes

for reference, this is called roulette wheel selection, or fitness proportionate selection.

5 Likes