shuffle

function shuffle( arr [, seed] ) --> rar

Description

Returns a shuffled copy of the array table, using a version of the Fisher-Yates shuffle. The function accepts an optional seed value to get a better randomness.

Parameters

arr

Array table with values that should be shuffled.

seed

Optional seed value for the algorithm.

Return Values

rar

Shuffled copy.

Code

--ZFUNC-shuffle-v1
local function shuffle( arr, seed ) --> rar
   if seed then math.randomseed( seed ) end
   local n = #arr
   local rar = {}
   for i, v in ipairs( arr ) do
      local r = math.random( i )
      rar[ i ] = rar[ r ]
      rar[ r ] = v
   end
   return rar
end

return shuffle

Examples

local t = require( "tapered" )
local shuffle = require( "shuffle" )

local like = require( "like" )

local arr = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }
t.ok( like( arr, shuffle( arr ) ) )

t.done()

Inspired by