我有两个数组:
@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 %>提前谢谢~
发布于 2011-02-16 16:06:14
您可以使用数组交集来执行此操作:
@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 %>发布于 2011-02-16 16:35:38
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}发布于 2017-06-06 23:25:18
要找出数组之间的总匹配数,请将它们相加,然后减去唯一集。超集数组和uniq集合的长度之差将是第一个数组中第二个数组的匹配计数。如果a2是唯一的集合,则此方法效果最好。
a1 = ['a','b','c','d','d','d']
a2 = ['a','d']
superset = (a1 + a2)
subset = superset.uniq
matches = superset.count - subset.counthttps://stackoverflow.com/questions/5013880
复制相似问题