Nishtha Nishtha - 1 year ago 42
Ruby Question

Ruby find combination

I am trying to take input as a string.

Then I need to find all the possible combination and distinct combination but I am unable to do so.

input = "aabb"

Output I need to print all Combination =


Now Distinct combination


Then I need to count the letters and do a summation


For this

result = 1+1+1+1+2+2+2+3+3+4

Similarly for the other combination I need to find summation.

Answer Source

You can use Array#combination.

To get all combinations:

input = "aabb"
res = []
input.size.times { |n| res << input.chars.combination(n+1).map { |a| a.join } }
#=> ["a", "a", "b", "b", "aa", "ab", "ab", "ab", "ab", "bb", "aab", "aab", "abb", "abb", "aabb"]

distinct combinations:

#=> ["a", "b", "aa", "ab", "bb", "aab", "abb", "aabb"]

to count the letters and do a summation:
#=> [1, 1, 2, 2, 2, 3, 3, 4]
# => 18