Last active
December 12, 2015 05:28
-
-
Save vderyagin/4722300 to your computer and use it in GitHub Desktop.
find all permutations of characters in given string
This file contains 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
def permutations(s) | |
return [s] if s.length == 1 | |
chars = s.chars.to_a | |
chars.each_with_object([]) do |ch, ps| | |
rest = chars.reject { |c| c.equal? ch }.join | |
permutations(rest).each do |perm| | |
ps << (ch + perm) | |
end | |
end | |
end | |
p permutations('abc') | |
# >> ["abc", "acb", "bac", "bca", "cab", "cba"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment