Created
March 25, 2014 22:00
-
-
Save cristobal/9772382 to your computer and use it in GitHub Desktop.
Lua implementation of Fisher-Yates Shuffle "inside-out"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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