簡體   English   中英

Ruby:比較2個匹配數組,並計算匹配實例的數量

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

我有2個數組:

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

我想比較兩個數組以找到匹配(d,e)並計算找到的匹配數(2)?

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

提前謝謝〜

您可以使用數組交集執行此操作:

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

@intersection現在應該是['d','e']。 然后,您可以執行以下操作:

<% if !@intersection.empty? %>
  <%= @intersection.size %> Matches Found.
<% else %>
  No Matches Found.
<% end %>

要查找陣列之間的總匹配數,請將它們一起添加,然后減去唯一集。 超集數組的長度與uniq集之間的差異將是第一個數組中第二個數組的匹配計數。 如果a2是唯一集合,則此方法效果最佳。

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

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

matches = superset.count - subset.count
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

首先,您只需添加兩個陣列

@array_sum = @array1 + @array2

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

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

或者查看如何計算Ruby Arrays中的重復項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM