mirror of
https://github.com/1bardesign/batteries.git
synced 2024-11-22 14:14:36 +00:00
added todo for tablex.weighted_random, removed returning the weight value as multi-return wasn't documented and could break in some circumstances
This commit is contained in:
parent
7aa476a58c
commit
31bfe92d37
11
tablex.lua
11
tablex.lua
@ -202,8 +202,11 @@ function tablex.take_random(t, r)
|
||||
return table.remove(t, tablex.random_index(t, r))
|
||||
end
|
||||
|
||||
--return a random index based on weights provided
|
||||
--Example: { 0.3, 1, 6, 0.5 } (3rd index most likely)
|
||||
--return a random index based on weights provided (or nil if it's empty)
|
||||
-- { 0.3, 1, 6, 0.5 } -> (3rd index most likely)
|
||||
-- possible todo:
|
||||
-- provide normalisation outside of this function, require normalised weights
|
||||
-- provide table of values _and_ weights and return the value
|
||||
function tablex.weighted_random(t, r)
|
||||
if #t == 0 then
|
||||
return nil
|
||||
@ -217,9 +220,11 @@ function tablex.weighted_random(t, r)
|
||||
for i, weight in ipairs(t) do
|
||||
sum = sum + weight
|
||||
if rnd <= sum then
|
||||
return i, weight
|
||||
return i
|
||||
end
|
||||
end
|
||||
--shouldn't get here but safety if using a random that returns >= 1
|
||||
return #t
|
||||
end
|
||||
|
||||
--shuffle the order of a table
|
||||
|
Loading…
Reference in New Issue
Block a user