Hello,
I’m looking for a function that can sort through a table of possibilities each with their own unique chance of occurring and pick one, but I also want it to account for multiples wherein the total chance is the product of all possibilities chosen.
Although Bronze & Silver was never written in the table of possibilities it can still occur with a rarity of 0.125 or in other words a 1 in 8 chance. The same logic applies to possibilities such as Bronze, Silver & Diamond and all number of possibilities. In this case with a table of 4 possibilities there should be a total of 2^4 (16) possibilities including combinations.
As a starting point you could edit this script, perhaps it will give you some ideas on how to achieve your system.
-- Function to calculate factorial
local function factorial(n)
if n == 0 then
return 1
else
return n * factorial(n - 1)
end
end
-- Function to generate combinations of items and their probabilities
local function generateCombinations(items)
local combinations = {}
local n = #items -- Number of items in the table
-- Loop through all possible combinations using binary representation
for i = 0, 2^n - 1 do
local combination = {}
local probability = 1.0
-- Check each bit of the binary representation
for j = 1, n do
if bit32.band(i, 2^(j-1)) ~= 0 then
table.insert(combination, items[j][1])
probability = probability * items[j][2]
end
end
-- Store the combination and its probability in the result table
if #combination > 0 then
table.insert(combinations, {table.concat(combination, ", "), probability})
end
end
return combinations
end
-- Main function to get a random item or combination from the table
function GetRandom(items)
-- Generate all possible combinations with their probabilities
local combinations = generateCombinations(items)
-- Select a random combination based on the calculated probabilities
local totalProbability = 0
for _, combo in ipairs(combinations) do
totalProbability = totalProbability + combo[2]
end
local randomValue = math.random() * totalProbability
local accumulatedProbability = 0
for _, combo in ipairs(combinations) do
accumulatedProbability = accumulatedProbability + combo[2]
if randomValue <= accumulatedProbability then
return combo[1] .. " - " .. string.format("%.4f", combo[2])
end
end
return "No item selected" -- This should never happen
end
-- Example usage
local Items = {
{"Bronze", 0.5},
{"Silver", 0.25},
{"Gold", 0.1},
{"Diamond", 0.01}
}
-- Test the GetRandom function
for i = 1, 8 do -- Adjust the number of trials as needed
warn(GetRandom(Items))
end