How can a script pick one of these fruits randomly, but their number effects the chance of them getting picked. The higher the number the lower the chance
(I have looked into this, I personally cant figure it out and every RNG system I find online works the opposite way)
local tab = {
["Apple"] = 1;
["Banana"] = 3;
["Pineapple"] = 10;
["Watermelon"] = 100;
}
local randomize = math.random(1, #tab)
print(randomize)
if randomize > 10 then --if its lower than 10 which should be rare
--code here
end
There have been similar posts on here very recently so I’m surprised you haven’t found an answer looking through those.
If you have a table of values like that I think it makes more sense to work the other way round. I.e. larger values mean more likely as this way it is more like weight dice. It also means that the values are proportional to the probabilty of that row.
local fruitWeights = {
Apple = 100
Banana = 33
Pineapple = 10
Watermelon = 1
}
local function getRandomItem(weights)
-- first step is to normalise the values to get the probabilities
local total = 0
for _, value in pairs(weights) do
total += value
end
-- probabilities are then given by (value/weight)
local outcomeArray = {}
for key, value in pairs(weights) do
table.insert(outcomeArray, {key = key, probability = value/total})
end
-- sort by least likely outcome first
table.sort(outcomeArray, function(a, b) return a.probability < b.probability end)
-- pick the outcome
local randomNumber = math.random()
for _, outcome in ipairs(outcomArray) do
if outcome.probability < randomNumber then return outcome.key end
end
end
function frute()
local pick = "Watermelon"
local rnd = math.random(1, 100)
if rnd == 1 then pick = "Apple"
elseif rnd < 4 then pick = "Banana"
elseif rnd < 11 then pick = "Pineapple"
end return pick
end
print(frute())