Nishtha - 1 year ago 42

Ruby Question

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 =

`'a','a','b','b','aa','ab','bb','aab','abb','aabb'`

Now Distinct combination

`'a','b','aa','ab','bb','aab','abb','aabb'`

Then I need to count the letters and do a summation

`'a','a','b','b','aa','ab','bb','aab','abb','aabb'`

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 } }
res.flatten
#=> ["a", "a", "b", "b", "aa", "ab", "ab", "ab", "ab", "bb", "aab", "aab", "abb", "abb", "aabb"]
```

distinct combinations:

```
res.flatten.uniq
#=> ["a", "b", "aa", "ab", "bb", "aab", "abb", "aabb"]
```

to count the letters and do a summation:

```
res.flatten.uniq.map(&:size)
#=> [1, 1, 2, 2, 2, 3, 3, 4]
res.flatten.uniq.map(&:size).reduce(:+)
# => 18
```