Skip to content

Instantly share code, notes, and snippets.

@neomantra
Last active December 14, 2015 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neomantra/5102312 to your computer and use it in GitHub Desktop.
Save neomantra/5102312 to your computer and use it in GitHub Desktop.
permute_string: returns a table of all permutations of `str`
--- returns a table of all permutations of `str`
local function permute_string( str )
local string_byte, string_char = string.byte, string.char
local src = {}
for i = 1, #str do
src[i] = string_byte( str, i )
end
local perm = {}
local permute_fn
permute_fn = function( a, n )
if n == 0 then
perm[string_char(unpack(a))] = true
else
for i = 1, n do
a[i], a[n] = a[n], a[i]
permute_fn( a, n - 1 )
a[i], a[n] = a[n], a[i]
end
end
end
permute_fn( src, #src )
local ret = {}
for k, _ in pairs(perm) do
ret[#ret+1] = k
end
return ret
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment