Created
February 22, 2015 20:08
-
-
Save rtoal/64627ffb89111dc3c2cb to your computer and use it in GitHub Desktop.
Heap's permutation algorithm as a Lua 5.3 commandline script
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
if #arg ~= 1 then | |
io.stderr:write('Exactly one argument required\n') | |
os.exit(1) | |
end | |
function generatePermutations(n, a) | |
if n == 0 then | |
print(utf8.char(table.unpack(a))) | |
else | |
for i = 1, n do | |
generatePermutations(n-1, a) | |
swapIndex = n % 2 == 0 and i or 1 | |
a[swapIndex], a[n] = a[n], a[swapIndex] | |
end | |
end | |
end | |
word = {utf8.codepoint(arg[1], 1, utf8.len(arg[1]))} | |
generatePermutations(#word, word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment