Guest User

Untitled

a guest
Dec 12th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.58 KB | None | 0 0
  1. -- Heap’s algorithm for all permutations
  2.  
  3. function printResult (a)
  4. for _,v in ipairs(a) do
  5. io.write(v, " ")
  6. end
  7. io.write("\n")
  8. end
  9.  
  10. function heap (a, n)
  11. n = n or #a
  12. if n <= 1 then
  13. coroutine.yield(a)
  14. else
  15. for i=1,n-1 do
  16. heap(a, n-1)
  17. if n%2 == 0 then
  18. a[n], a[i] = a[i], a[n]
  19. else
  20. a[n], a[1] = a[1], a[n]
  21. end
  22. end
  23. heap(a, n-1)
  24. end
  25. end
  26.  
  27. function permutations (a)
  28. return coroutine.wrap(function () heap(a) end)
  29. end
  30.  
  31. -- test
  32. for p in permutations{1,2,3,4} do
  33. printResult(p)
  34. end
Add Comment
Please, Sign In to add comment