Skip to content

Instantly share code, notes, and snippets.

@TeoTwawki
Last active April 6, 2019 08:40
Show Gist options
  • Save TeoTwawki/87d5dab7e4515f4a2981df7ea8e0a798 to your computer and use it in GitHub Desktop.
Save TeoTwawki/87d5dab7e4515f4a2981df7ea8e0a798 to your computer and use it in GitHub Desktop.
Weighted Random Selection in pure Lua
function WeightedRandomSelect(tableID)
local outerTable =
{
[1] =
{
{weightValue, thingValue},
{weightValue, thingValue}
},
[2] =
{
{weightValue, thingValue},
{weightValue, thingValue}
},
}
-- Use the input to select which inner table we are working with
local innerTable = outerTable[tableID]
local totalWeight = 0
-- Sum the weight values
for _, weight in ipairs(innerTable) do
totalWeight = totalWeight + innerTable[weight][1]
end
-- Generate random number from 1 to the total weight
local weightSelect = math.random(1, totalWeight)
local thisThing = 0
-- Check every row of the inner table till we find one smaller than our random number, then return it
for sumdumvar, weight in ipairs(innerTable) do
thisThing = thisThing+(innerTable[sumdumvar][1])
if (weightSelect < thisThing) then
return innerTable[sumdumvar][2]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment