thedeepfield
thedeepfield

Reputation: 6196

Ruby: Compare 2 arrays for matches, and count the number of match instances

I have 2 arrays:

@array1 = [a,b,c,d,e]
@array2 = [d,e,f,g,h]

I want to compare the two arrays to find matches (d,e) and count the number of matches found (2)?

<% if @array2.include?(@array1) %>
  # yes, but how to count instances?
<% else %>
  no matches found...
<% end %>

Thanks in advance~

Upvotes: 31

Views: 33235

Answers (3)

vanboom
vanboom

Reputation: 1332

To find the number of total matches between the arrays, add them together, then subtract the unique set. The difference between the length of the superset array and the uniq set will be the count of the matches of the second array in the first. This method works best if a2 is a unique set.

a1 = ['a','b','c','d','d','d']
a2 = ['a','d']

superset = (a1 + a2)
subset = superset.uniq

matches = superset.count - subset.count

Upvotes: 1

kriysna
kriysna

Reputation: 6168

class Array
  def dup_hash
    inject(Hash.new(0)) { |h,e| h[e] += 1; h }.select { 
      |k,v| v > 1 }.inject({}) { |r, e| r[e.first] = e.last; r }
  end
end

First you just add both arrays

@array_sum = @array1 + @array2

output = [a,b,c,d,e,d,e,f,g,h]

@array_sum.dub_hash => {d => 2, e => 2}

Or check this How to count duplicates in Ruby Arrays

Upvotes: 0

Pan Thomakos
Pan Thomakos

Reputation: 34340

You can do this with array intersection:

@array1 = ['a', 'b', 'c', 'd', 'e']
@array2 = ['d', 'e', 'f', 'g', 'h']
@intersection = @array1 & @array2

@intersection should now be ['d', 'e']. You can then do the following:

<% if [email protected]? %>
  <%= @intersection.size %> Matches Found.
<% else %>
  No Matches Found.
<% end %>

Upvotes: 82

Related Questions