I believe you can do something along the lines of this to introduce sort-of a “rarity” aspect to a favored range of numbers by implementing 2 math.random().
In the below code, if the initial random() call yields anything under 10, the condition will then proceed to “favor” or “bias” towards the secondary range of “lower” or “smaller” numbers considering the chances of the initial math.random() returning exactly 10 is statistically low.
local function generateNum(lowest, highest)
local num
if math.random(1, 10) < 10 then
num = math.random(lowest, math.floor(highest/2) - 1) -- Divided range of "lower" numbers (from the originally supplied range)
else
num = math.random(math.floor(highest/2), highest) -- Divided range of "higher" / "rarer" numbers (from the originally supplied range)
end
return num
end
local randomNumber = generateNum(1, 100) -- The total range (but with a bias towards lowere numbers)
print(randomNumber)
for amount = 0, randomNumber, 1 do
-- Execute your code
end
I’m not fully sure of how reliable this logic would be, but you may amend this to further yield the intended result to match your needs.
EDIT:
I’ve just updated the function to now take in a total range with lowest and highest possible points. The function then divides the range into 2 different ranges of its own, the lower half, and the upper half. Although, the function will operate with a bias towards the lower half (making the upper half rarer).
Hopefully this helps lead you in the right direction.
From what your describing it sounds like you need the use of Weighted Probabilities.
This code example below also implies the further you get down to the max value the rarer it gets for it to be picked.
Hope this helps
function create_weighted_table(min, max)
local weightedTable = {}
for i = min, max do
local weight = max - i + min
table.insert(weightedTable, {i, weight})
end
return weightedTable
end
function weighted_random(weightedTable)
local totalWeight = 0
for i = 1, #weightedTable do
totalWeight = totalWeight + weightedTable[i][2]
end
local rand = math.random(totalWeight)
for i = 1, #weightedTable do
rand = rand - weightedTable[i][2]
if rand <= 0 then
return weightedTable[i][1]
end
end
end
-- Specify your desired range
local min = 1
local max = 100
local weightedTable = create_weighted_table(min, max) -- Create weighted table
local number = weighted_random(weightedTable)
print(number) -- Number picked
for i = 1, number do
-- here are some things I want to do
end