Changed lume.shuffle() to not operate in-place, updated doc + tests

This commit is contained in:
rxi
2015-01-10 16:21:57 +00:00
parent ac10d54b47
commit 4373a202dc
3 changed files with 9 additions and 5 deletions

View File

@@ -75,7 +75,7 @@ lume.weightedchoice({ ["cat"] = 10, ["dog"] = 5, ["frog"] = 0 })
``` ```
### lume.shuffle(t) ### lume.shuffle(t)
Shuffles the values of array `t` in place, returns the array. Returns a shuffled copy of the array `t`.
### lume.array(...) ### lume.array(...)
Iterates the supplied iterator and returns an array filled with the values. Iterates the supplied iterator and returns an array filled with the values.

View File

@@ -146,11 +146,15 @@ end
function lume.shuffle(t) function lume.shuffle(t)
local rtn = {}
for i = 1, #t do for i = 1, #t do
local r = math_random(#t) local r = math_random(i)
t[i], t[r] = t[r], t[i] if r ~= i then
rtn[i] = rtn[r]
end
rtn[r] = t[i]
end end
return t return rtn
end end

View File

@@ -109,7 +109,7 @@ end
-- lume.shuffle -- lume.shuffle
tests["lume.shuffle"] = function() tests["lume.shuffle"] = function()
local t = {1, 2, 3, 4, 5} local t = {1, 2, 3, 4, 5}
lume.shuffle(t) t = lume.shuffle(t)
table.sort(t) table.sort(t)
testeq( t, {1, 2, 3, 4, 5} ) testeq( t, {1, 2, 3, 4, 5} )
testeq( lume.shuffle({}), {} ) testeq( lume.shuffle({}), {} )