Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Heap’s algorithm for all permutations
- function printResult (a)
- for _,v in ipairs(a) do
- io.write(v, " ")
- end
- io.write("\n")
- end
- function heap (a, n)
- n = n or #a
- if n <= 1 then
- coroutine.yield(a)
- else
- for i=1,n-1 do
- heap(a, n-1)
- if n%2 == 0 then
- a[n], a[i] = a[i], a[n]
- else
- a[n], a[1] = a[1], a[n]
- end
- end
- heap(a, n-1)
- end
- end
- function permutations (a)
- return coroutine.wrap(function () heap(a) end)
- end
- -- test
- for p in permutations{1,2,3,4} do
- printResult(p)
- end
Add Comment
Please, Sign In to add comment