Skip to content

Instantly share code, notes, and snippets.

@cristobal
Created March 25, 2014 22:00
Show Gist options
  • Save cristobal/9772382 to your computer and use it in GitHub Desktop.
Save cristobal/9772382 to your computer and use it in GitHub Desktop.
Lua implementation of Fisher-Yates Shuffle "inside-out"
-- Remember to seed outside the function i.e. at top of your script
-- especially on OSX otherwise you will get the same permutations.
-- math.randomseed(os.time())
-- More info http://lua-users.org/wiki/MathLibraryTutorial
function random(min, max)
if (max == null) then
max = min
min = 0
end
return min + math.floor(math.random() * (max - min + 1))
end
function shuffle(list)
local shuffled = {}
local len = 0
for k, v in pairs(list) do
j = random(0, len)
if j == len then
table.insert(shuffled, v)
else
table.insert(shuffled, shuffled[j + 1])
shuffled[j + 1] = v
end
len = len + 1
end
return shuffled
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment