Skip to content

Instantly share code, notes, and snippets.

@vderyagin
Last active December 12, 2015 05:29
Show Gist options
  • Save vderyagin/4722402 to your computer and use it in GitHub Desktop.
Save vderyagin/4722402 to your computer and use it in GitHub Desktop.
Find all combinations of characters in given string
def combinations(s)
return [s] if s.length == 1
chars = s.chars.to_a
chars.each_with_object([]) do |ch, cs|
rest = chars.drop(chars.find_index(ch) + 1).join
cs << ch
combinations(rest).each do |comb|
cs << (ch + comb)
end
end
end
p combinations('wxyz')
# >> ["w", "wx", "wxy", "wxyz", "wxz", "wy", "wyz", "wz", "x", "xy", "xyz", "xz", "y", "yz", "z"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment