Skip to content

Instantly share code, notes, and snippets.

@wilbefast
Last active August 29, 2015 14:06
Show Gist options
  • Save wilbefast/0d17085448475b93cdcf to your computer and use it in GitHub Desktop.
Save wilbefast/0d17085448475b93cdcf to your computer and use it in GitHub Desktop.
Shuffling tables and iterating them in a random order
--[[
What if you want to pick a random option but you're not sure if that random option will be valid?
Instead of doing a while loop and hoping that you'll eventually land on a valid option
try shuffling the list of options and trying each one in this random order ;)
W.
--]]
local shuffle = function(table) -- standard Fisher-Yates implementation
for i = #table, 2, -1 do
local j = math.random(1, i)
local swap = table[i]
table[i] = table[j]
table[j] = swap
end
return t
end
local random_iter = function(table, func)
local indices = {}
for i = 1, #table do
indices[i] = i
end
shuffle(indices)
for i = 1, #indices do
func(table[indices[i]])
end
end
return { shuffle = shuffle, random_iter = random_iter }
local shuffle = require("shuffle")
local is_valid = function(option)
return not option.used
end
local all_options = { { "foo" }, { "bar" }, { "foobar"} }
.
local do_stuff = function(option)
print(option[1])
option.used = true
end
local finished = false
shuffle.random_iter(all_options, function(option)
if finished or (not is_valid(option)) then
return
end
do_stuff(option)
finished = true
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment