Skip to content

Instantly share code, notes, and snippets.

@Bradshaw
Forked from wilbefast/shuffle.lua
Last active August 29, 2015 14:06
Show Gist options
  • Save Bradshaw/32e3b44b9eed40f887b0 to your computer and use it in GitHub Desktop.
Save Bradshaw/32e3b44b9eed40f887b0 to your computer and use it in GitHub Desktop.
--[[
What if you want to pick a random option but you're not sure if that random option will be valid?
Let's do this without shufflin' , yeah?
--]]
local randopick = function(table, func)
local indices = {}
for i = 1, #table do
indices[i] = i
end
local size = #indices -- indices is going to change size, I'm not sure what this does to "for i= 1, #indices"
for i = 1, size do
local ind = math.random(1,#indices) -- Grab an card, any card
if func(table[indices[ind]]) then -- Do something with it
break -- break if we're done
end
table.remove(indices, ind) -- Chuck it...
end
end
return {randopick = randopick}
--[[
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)
table[i], table[j] = table[j], table[i] -- Lua, bro... - Kev.
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 randopick = require("randopick")
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
randopick.randopick(all_options, function(option)
if(not is_valid(option)) then
return false
end
do_stuff(option)
return true
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment