mirror of
https://github.com/TangentFoxy/lume.git
synced 2025-07-28 11:02:20 +00:00
Changed lume.shuffle() to not operate in-place, updated doc + tests
This commit is contained in:
@@ -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.
|
||||||
|
10
lume.lua
10
lume.lua
@@ -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
|
||||||
|
|
||||||
|
|
||||||
|
@@ -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({}), {} )
|
||||||
|
Reference in New Issue
Block a user