Advertisement
CluelessDev

Weighted choice module

Dec 19th, 2021
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.90 KB | None | 0 0
  1. -- table MUST be a dictionary and have a weight entry!
  2. local function CalculateMaxWeight(aTable)
  3.     local result = 0
  4.  
  5.     -- add all entries weights together, to get one big value
  6.     for _, entry in pairs(aTable) do
  7.         result = result + entry.Weight
  8.     end
  9.  
  10.     return result
  11. end
  12.  
  13. return function(aWeightedTable)
  14.     -- Choose a random number between 0 and the max weight
  15.     local MaxWeight = CalculateMaxWeight(aWeightedTable)
  16.     local randI = math.random(MaxWeight)
  17.    
  18.     -- iterate the entries to see wich will be choosed based on their weight
  19.     for _, entry in pairs(aWeightedTable) do
  20.         -- the random number is lower than the current entry weight? Tehn return me that entry IT WAS SELECTED
  21.         if randI <= entry.Weight then
  22.             return entry      
  23.         else -- Substract and keep rolling
  24.             randI = randI - entry.Weight  
  25.         end
  26.     end
  27. end
  28.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement