Skip to content

Instantly share code, notes, and snippets.

@vderyagin
Last active December 12, 2015 05:28
Show Gist options
  • Save vderyagin/4722300 to your computer and use it in GitHub Desktop.
Save vderyagin/4722300 to your computer and use it in GitHub Desktop.
find all permutations of characters in given string
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