Skip to content

Instantly share code, notes, and snippets.

@saga
Created December 7, 2011 09:38
Show Gist options
  • Save saga/1442179 to your computer and use it in GitHub Desktop.
Save saga/1442179 to your computer and use it in GitHub Desktop.
local print = print
function permgen (a, n)
print ("-- permgen begin, n: " .. n)
if n == 0 then
printResult(a)
else
for i=1,n do
-- put i-th element as the last one
local str = " --- switch " .. n .. " - " .. i .. ", value " .. a[n] .. " - " .. a[i]
print(str)
a[n], a[i] = a[i], a[n]
-- generate all permutations of the other elements
permgen(a, n - 1)
-- restore i-th element
a[n], a[i] = a[i], a[n]
end
end
print("-- permgen end, n: " .. n)
end
function printResult (a)
for i,v in ipairs(a) do
io.write(v, " ")
end
io.write("\n")
end
-- permgen ({1,2,3,4,5}, 4)
function perm (a)
local n = table.getn(a)
print("-- in perm begin, n:" .. n)
local co = coroutine.create(function ()
permgen(a, n)
end)
print("-- in perm, create co, will return with co.resume")
return function () -- iterator
local code, res = coroutine.resume(co)
if res ~= nil then
print("after resume, res:" .. res)
else
print("after resume, nil")
end
return res
end
end
for p in perm{1,2,3,4} do
printResult(p)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment