Created
December 7, 2011 09:38
-
-
Save saga/1442179 to your computer and use it in GitHub Desktop.
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 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