Skip to content

Commit

Permalink
added shuffle-array
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisdugne committed May 29, 2020
1 parent 3f283eb commit abe6853
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ rocks:
@${rocksDir}/bin/luarocks install --tree ${rocksDir} luacov
@${rocksDir}/bin/luarocks install --tree ${rocksDir} luacheck
@${rocksDir}/bin/luarocks install --tree ${rocksDir} busted
@${rocksDir}/bin/luarocks install --tree ${rocksDir} luasocket

luacheck:
@${rocksDir}/bin/luacheck .
Expand Down
27 changes: 27 additions & 0 deletions cherry/libs/shuffle-array.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
------------------------------------------------------------------

local time = require 'cherry.libs.time'

------------------------------------------------------------------
-- https://stackoverflow.com/a/12646864
-- Randomize array in-place using Durstenfeld shuffle algorithm
------------------------------------------------------------------
-- this function mutates the array
------------------------------------------------------------------

local function shuffleArray(array)
local seed = time.getTimeMs()
math.randomseed(seed)

for i = #array, 1, -1 do
local j = math.floor(math.random() * i) + 1
print(i, j)
local temp = array[i]
array[i] = array[j]
array[j] = temp
end
end

------------------------------------------------------------------

return shuffleArray

0 comments on commit abe6853

Please sign in to comment.