Created
December 27, 2014 07:31
-
-
Save DamonHao/9ba2865b11344b2de7ad to your computer and use it in GitHub Desktop.
Lua, permutation with coroutine
This file contains hidden or 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 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