Skip to content

Instantly share code, notes, and snippets.

@rtoal
Created February 22, 2015 20:08
Show Gist options
  • Save rtoal/64627ffb89111dc3c2cb to your computer and use it in GitHub Desktop.
Save rtoal/64627ffb89111dc3c2cb to your computer and use it in GitHub Desktop.
Heap's permutation algorithm as a Lua 5.3 commandline script
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