Last active
August 29, 2015 14:06
-
-
Save wilbefast/0d17085448475b93cdcf to your computer and use it in GitHub Desktop.
Shuffling tables and iterating them in a random order
This file contains 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
--[[ | |
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 } |
This file contains 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
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