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( "taptest" )
local like = require( "like" )
local same = require( "same" )
local shuffle = require( "shuffle" )

local arr = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }
local shuffled = shuffle( arr )
t( like( arr, shuffled ), true )
t( same( arr, shuffled ), false )

t()

Inspired by