比较包括重复的数组元素 [英] Comparing array elements including duplicates
问题描述
我正在尝试查看一个数组是否包含另一个数组的每个元素。另外我想说明重复的事项。例如:
I am trying to see if an array contains each element of another array. Plus I want to account for the duplicates. For example:
array = [1, 2, 3, 3, "abc", "de", "f"]
数组包含[1,2,3,3],但不包含[2,2, abc] - 太多2的
array contains [1, 2, 3, 3] but does not contain [2, 2, "abc"] - too many 2's
我已经尝试了下面,但显然没有考虑到这些重复。
I have tried the below but obviously doesn't take into account the dupes.
other_arrays.each { |i| array.include? i }
推荐答案
此方法在两个数组上迭代一次。
对于每个数组,它创建一个散列,每个元素的出现次数。
This method iterates once over both arrays. For each array, it creates a hash with the number of occurences of each element.
然后检查子集
, 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
class可以定义:
If you don't want to patch the Array
class, you could define :
count_by(array)
和 subset_of? (array1,array2)
。
这篇关于比较包括重复的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!