Last active
April 6, 2019 08:40
-
-
Save TeoTwawki/87d5dab7e4515f4a2981df7ea8e0a798 to your computer and use it in GitHub Desktop.
Weighted Random Selection in pure Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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