【问题标题】:Comparing array elements including duplicates比较数组元素,包括重复项
【发布时间】:2017-06-19 21:24:58
【问题描述】:

我正在尝试查看一个数组是否包含另一个数组的每个元素。另外,我想考虑重复项。例如:

array = [1, 2, 3, 3, "abc", "de", "f"]

数组包含 [1, 2, 3, 3] 但不包含 [2, 2, "abc"] - 2 太多

我已经尝试了以下方法,但显然没有考虑到欺骗。

other_arrays.each { |i| array.include? i }

【问题讨论】:

  • 类似使用.all?方法other_arrays.all? {|x| array.include? x }

标签: arrays ruby duplicates comparison


【解决方案1】:

此方法在两个数组上迭代一次。 对于每个数组,它会创建一个包含每个元素出现次数的哈希。

然后,它检查subset 中的每个唯一元素,superset 中的元素数量是否至少相同。

class Array
  def count_by
    each_with_object(Hash.new(0)) { |e, h| h[e] += 1 }
  end

  def subset_of?(superset)
    superset_counts = superset.count_by
    count_by.all? { |k, count| superset_counts[k] >= count }
  end
end

[1, 2, 3, 3, "abc", "de", "f"].count_by
#=> {1=>1, 2=>1, 3=>2, "abc"=>1, "de"=>1, "f"=>1}

[1, 2, 3, 3].count_by
#=> {1=>1, 2=>1, 3=>2}

[1, 2, 3, 3].subset_of? [1, 2, 3, 3, "abc", "de", "f"]
#=> true
[2, 2, "abc"].subset_of? [1, 2, 3, 3, "abc", "de", "f"]
#=> false

如果您不想修补 Array 类,您可以定义:

count_by(array)subset_of?(array1, array2)

【讨论】:

    【解决方案2】:

    你可以先为Array类创建一个有用的实例方法:

    class Array
      def difference(other)
        h = other.each_with_object(Hash.new(0)) { |e,h| h[e] += 1 }
        reject { |e| h[e] > 0 && h[e] -= 1 }
      end
    end
    

    如果以下方法返回true,则数组a的所有元素都包含在数组b中。

    def subarray?(a,b)
      a.difference(b).empty?
    end
    

    例如,

    subarray? [1,2,3], [1,4,"cat",3,2]
      #=> true
    subarray? [1,2,3], [1,4,"cat",3,5]
      #=> false
    

    我发现Array#difference 有如此广泛的应用,我proposed 将它添加到Ruby 核心。有关该方法及其用途的详细信息,请参见链接以及我对this SO 问题的回答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 2016-03-25
      • 2019-08-05
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多