Created
February 5, 2015 17:10
-
-
Save georgi/4d51c8712f11d7d38c90 to your computer and use it in GitHub Desktop.
String permutations
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
# 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