This should be a very simple question to answer for anyone who is good at math. I did not learn what I am trying to do and I couldn’t find anything online to solve my problem as I do not know what it is called.
I have a table of chances:
local exampleChances = {
common = 50,
rare = 30,
epic = 20
}
It adds up to 100.
I insert them into a table with their name the amount of times shown in the value. I then choose a random one.
What I would like to do is implement a twist in the mechanic where there is “luck”: a level from 1-5 that increases chances for certain categories.
Now I’m sure the way I am using to calculate the random category is not as good as it can be, so if someone could provide a better solution to that, it would be appreciated.
What I would like to solve though is the luck mechanic. Is there a formula or something that could possibly help me achieve this?
My code:
for name, chance in chances do
for _ = chance, 0, -1 do
table.insert(chances, name)
end
end
print(chances[math.random(1, #chances)]) --> common, uncommon, or rare
Have you thought about luck simply modifying the base chances? For instance a normal person has an epic chance of 20, but you could make that variable based on luck, so someone with a higher luck level has a chance of 30 instead. Maybe make a formula for each chance based on luck stat. E.g epic = 20 + luck.
If you still want it to add up to 100, just subtract luck from common and maybe add 2/3 of the luck to rare, and 1/3 to epic.
To do this, add up all the values, find their lowest value and their highest value and do an RNG function that goes up to the total. Like, for example, Common would be 1, 50, Rare would be 51, 80 and Epic to 81, 100, Then loop through those and check if your RNG lands on one of them. You are basically lining the chances up on a number line.
If done correctly, you should have your randomly-generated chance.
local items = {
game.ServerStorage.Item1,
game.ServerStorage.Item2,
game.ServerStorage.Item3,
game.ServerStorage.Item4,
}
local chances = {
{1000, 100, 10, 1}, -- chances with luck 1
{800, 90, 15, 2}, -- chances with luck 2
{600, 80, 20, 4}, -- chances with luck 3
}
-- work out the totals
local totals = {}
for i, list in ipairs(chances) do
totals[i] = 0
for j, chance in ipairs(list) do
totals[i] += chance
end
end
local function SelectRandom(luck)
local random = math.random(totals[luck])
for i, chance in ipairs(chances[luck]) do
random -= chance
if random > 0 then continue end
return items[i]
end
end
print(SelectRandom(1)) -- pick a item with 1 luck
print(SelectRandom(1)) -- pick a item with 1 luck
print(SelectRandom(2)) -- pick a item with 2 luck
print(SelectRandom(2)) -- pick a item with 2 luck
print(SelectRandom(3)) -- pick a item with 3 luck
print(SelectRandom(3)) -- pick a item with 3 luck
total = 1000 + 100 + 10 + 1 = 1111
1000 in 1111 chance 1000/1111*100 = 90.0090009001%