Skip to content

Instantly share code, notes, and snippets.

@DamonHao
Created December 27, 2014 07:31
Show Gist options
  • Select an option

  • Save DamonHao/9ba2865b11344b2de7ad to your computer and use it in GitHub Desktop.

Select an option

Save DamonHao/9ba2865b11344b2de7ad to your computer and use it in GitHub Desktop.
Lua, permutation with coroutine
local function printResult(a)
for i = 1, #a do
io.write(a[i], " ")
end
io.write("\n")
end
local function permgen (a, n)
n = n or #a
if n <= 1 then
coroutine.yield(a)
else
for i = 1, n do
a[i], a[n] = a[n], a[i]
permgen(a, n-1)
a[i], a[n] = a[n], a[i]
end
end
end
local function permutations(a)
local co = coroutine.create(function () permgen(a) end)
return function ()
local code, res = coroutine.resume(co)
return res
end
end
local function test()
for p in permutations({"a", "b", "c"}) do
printResult(p)
end
end
local function main()
test()
end
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment