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)
Shuffles the values of array `t` in place, returns the array.
Returns a shuffled copy of the array `t`.
### lume.array(...)
Iterates the supplied iterator and returns an array filled with the values.

View File

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

View File

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