【问题标题】:Ruby: Compare 2 arrays for matches, and count the number of match instancesRuby:比较 2 个数组的匹配项,并计算匹配实例的数量
【发布时间】:2011-02-16 07:58:31
【问题描述】:

我有 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 %>

先谢谢了~

【问题讨论】:

    标签: ruby-on-rails ruby arrays


    【解决方案1】:

    你可以用数组交集来做到这一点:

    @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 %>
    

    【讨论】:

      【解决方案2】:

      要查找数组之间的总匹配数,请将它们相加,然后减去唯一集。超集数组和 uniq 集的长度之间的差异将是第一个数组中第二个数组的匹配数。如果 a2 是唯一集,则此方法效果最佳。

      a1 = ['a','b','c','d','d','d']
      a2 = ['a','d']
      
      superset = (a1 + a2)
      subset = superset.uniq
      
      matches = superset.count - subset.count
      

      【讨论】:

        【解决方案3】:
        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}
        

        或查看How to count duplicates in Ruby Arrays

        【讨论】:

        • 如果您有超过 2 个数组,这将很有帮助
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-04
        • 2017-07-29
        • 2020-02-08
        • 1970-01-01
        相关资源
        最近更新 更多