Skip to content

Instantly share code, notes, and snippets.

@georgi
Created February 5, 2015 17:10
Show Gist options
  • Save georgi/4d51c8712f11d7d38c90 to your computer and use it in GitHub Desktop.
Save georgi/4d51c8712f11d7d38c90 to your computer and use it in GitHub Desktop.
String permutations
# Returns all permutations of string s
def permutations(s)
# For single characters just return one solution, the character
if s.size <= 1
[s]
else
# calculate all permutations without the first character
# and then iterate over each
permutations(s[1..-1]).flat_map do |x|
# for each position in permutation x
0.upto(x.size).map do |i|
# insert the first character into permutation x
x.dup.insert(i, s[0])
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment