Modified weighted random pick function

- Now accepts a table from which it will pick the random value from,
  instead of an index
- Changed function name to better reflect the way it now works
This commit is contained in:
Jesse Viikari 2021-11-18 11:08:29 +02:00
parent 6ce0dfa523
commit a42f1190e0

View File

@ -202,29 +202,28 @@ function tablex.take_random(t, r)
return table.remove(t, tablex.random_index(t, r)) return table.remove(t, tablex.random_index(t, r))
end end
--return a random index based on weights provided (or nil if it's empty) --return a random value from table based on weights provided (or nil if it's empty)
-- { 0.3, 1, 6, 0.5 } -> (3rd index most likely) -- w: weights, t: table to pick value from
-- possible todo: -- possible todo:
-- provide normalisation outside of this function, require normalised weights -- provide normalisation outside of this function, require normalised weights
-- provide table of values _and_ weights and return the value function tablex.pick_weighted_random(t, w, r)
function tablex.weighted_random(t, r) if #w == 0 or #t == 0 then
if #t == 0 then
return nil return nil
end end
local sum = 0 local sum = 0
for _, weight in ipairs(t) do for _, weight in ipairs(w) do
sum = sum + weight sum = sum + weight
end end
local rnd = _random(nil, nil, r) * sum local rnd = _random(nil, nil, r) * sum
sum = 0 sum = 0
for i, weight in ipairs(t) do for i, weight in ipairs(w) do
sum = sum + weight sum = sum + weight
if rnd <= sum then if rnd <= sum then
return i return t[i]
end end
end end
--shouldn't get here but safety if using a random that returns >= 1 --shouldn't get here but safety if using a random that returns >= 1
return #t return tablex.back(t)
end end
--shuffle the order of a table --shuffle the order of a table