-2

Input:

a = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]

How to list out no of pairs in an array.

Output:

9

Description

#no 1(1 pair)
#no 3(1 pair)
#no 4(2 pairs)
#no 5(3 pairs)
#no 6(2 pairs)
#so total 9 pairs

3 Answers3

4

Here is another option:

a.group_by(&:itself).transform_values{ |v| v.size / 2 }.values.sum
#=> 9


How it works.

First group the elements by value:

a.group_by(&:itself) #=> {4=>[4, 4, 4, 4, 4], 5=>[5, 5, 5, 5, 5, 5], 6=>[6, 6, 6, 6, 6], 1=>[1, 1], 3=>[3, 3]}

Then transforming the keys to the pair count:

a.group_by(&:itself).transform_values{ |v| v.size / 2 } #=> {4=>2, 5=>3, 6=>2, 1=>1, 3=>1}

So, get the values of the hash:

a.group_by(&:itself).transform_values{ |v| v.size / 2 }.values #=> [2, 3, 2, 1, 1]

Finally, sum the values, which is the first line of code posted above.

iGian
  • 11,023
  • 3
  • 21
  • 36
1
arr = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]
hash = Hash.new(0)
arr.each { |e| hash[e] += 1 }
hash.values.reduce(0) { |s, n| s += n / 2 } // => 9

Since from what I can gather you are basically removing integers the moment they got paired once so technically it's just an integer division by two.

[1] How to count identical string elements in a Ruby array

[2] Reduce Hash Values

claasic
  • 1,050
  • 6
  • 14
  • 1
    Good answer. OP has edited title so the total number (9) is no longer asked for, so you might write `arr.each_with_object(Hash.new(0)) { |e,hash| hash[e] += 1 }.transform_values { |v| v/2 } #=> {4=>2, 5=>3, 6=>2, 1=>1, 3=>1}`. – Cary Swoveland May 28 '19 at 07:31
1

I have done like this, It works

  b = []
  a.uniq.each { |i| b.push(a.count(i)/2)}
  b.sum
  • 1
    Note that `count` has to traverse the entire array each time which makes this solution rather inefficient. – Stefan May 27 '19 at 14:30