Ruby find combination

Nishtha

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.

shivam

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Python: How to find most frequent combination of elements?

From Dev

Find most common combination of elements in several arrays

From Dev

Wobble Hypothesis - Combination or Permutation of Array of strings in ruby

From Dev

Find most frequent combination of numbers in a set

From Dev

Find letter combination on phone keypad

From Dev

Ruby's Array Combination Method

From Dev

Find Random BitshiftRight Combination

From Dev

Find sum from combination of array elements

From Dev

Ruby possible combination of array values - performance

From Dev

Rails: Find records with a certain combination of associated records

From Dev

Ruby - Hash - Combination

From Dev

Algorithm to find best dimensions combination

From Dev

Find combination of groups and letters

From Dev

Find all combination that sum to N with multiple lists

From Dev

What does this combination of chunk and map do in Ruby?

From Dev

faster n choose k for combination of array ruby

From Dev

Mongoose find on field combination

From Dev

Python equivalent for Ruby combination method

From Dev

Java: find combination days in a list

From Dev

How to identify ruby and gemset combination for rvm wrapper

From Dev

Find letter combination on phone keypad

From Dev

Every combination of elements in two Ruby arrays

From Dev

Ruby possible combination of array values - performance

From Dev

Ruby - Hash - Combination

From Dev

What does this combination of chunk and map do in Ruby?

From Dev

faster n choose k for combination of array ruby

From Dev

find the best combination of columns in a matrix

From Dev

Limiting the number of trials in combination Ruby

From Dev

Find combination that gives maximum profit

Related Related

HotTag

Archive