mirror of
https://github.com/1bardesign/batteries.git
synced 2024-11-25 23:24:35 +00:00
Merge pull request #40 from speakk/weighted_random
Add a weighted random pick for tablex
This commit is contained in:
commit
7aa476a58c
20
tablex.lua
20
tablex.lua
@ -202,6 +202,26 @@ 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
|
||||||
|
--Example: { 0.3, 1, 6, 0.5 } (3rd index most likely)
|
||||||
|
function tablex.weighted_random(t, r)
|
||||||
|
if #t == 0 then
|
||||||
|
return nil
|
||||||
|
end
|
||||||
|
local sum = 0
|
||||||
|
for _, weight in ipairs (t) do
|
||||||
|
sum = sum + weight
|
||||||
|
end
|
||||||
|
local rnd = _random(nil, nil, r) * sum
|
||||||
|
sum = 0
|
||||||
|
for i, weight in ipairs (t) do
|
||||||
|
sum = sum + weight
|
||||||
|
if rnd <= sum then
|
||||||
|
return i, weight
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
--shuffle the order of a table
|
--shuffle the order of a table
|
||||||
function tablex.shuffle(t, r)
|
function tablex.shuffle(t, r)
|
||||||
for i = 1, #t do
|
for i = 1, #t do
|
||||||
|
Loading…
Reference in New Issue
Block a user