如何判断数组是否包含另一个数组中的确切值以包含重复项?

时间:2021-08-15 19:29:21

I have two arrays:

我有两个数组:

a1 = [1,4,4,4,5,6]
a2 = [4,4,4]

I am trying to determine if a1 has exactly three 4s like a2.

我试图确定a1是否恰好有三个4s像a2。

I tried to use subset but it seems to exclude the duplicate values.

我试图使用子集,但它似乎排除了重复的值。

require 'set'
a1 = Set.new [1,4,4,4,5,6]
=> #<Set: {1, 4, 5, 6}> 
a2 = Set.new [4,4,4]
=> #<Set: {4}>
a2.subset?(a1)
=> true

This doesn't work because, when it creates the set, it ignores all duplicates.

这不起作用,因为当它创建集时,它会忽略所有重复项。

The same goes for:

同样适用于:

(a1 & a2) == a1

and:

(a2 & a1) == a2

3 个解决方案

#1


1  

You could use each_cons to break a1 into multiple chunks (i.e. [1,4,4], [4,4,4], [4,4,5], [4,5,6]). Then you could see if any of those chunks matches a2.

您可以使用each_cons将a1分成多个块(即[1,4,4],[4,4,4],[4,4,5],[4,5,6])。然后你可以看到这些块中是否有任何一个匹配a2。

a1 = [1,4,4,4,5,6]
a2 = [4,4,4]

a1.each_cons(3).include?(a2)
# => true

a1 = [1,4,5,6,4,4]
a1.each_cons(3).include?(a2)
# => false

#2


1  

>> a1 = [1,4,4,4,5,6]
>> a2 = [4,4,4]
>> a1.count(4) == 3 # => true
>> a1.count(4) == a2.count(4) # => true

#3


0  

If you run Enumerable#find_all on an array, it will return an array of all found elements.

如果在数组上运行Enumerable#find_all,它将返回所有找到的元素的数组。

For this particular problem, as falsetru answered, Enumerable#count is much easier and more readable.

对于这个特殊问题,正如falsetru回答的那样,Enumerable #count更容易,更易读。

Note: That will also return true if both arrays have 0 of an element:

注意:如果两个数组都有0个元素,那么它也将返回true:

def same_amounts?(ar1, ar2, ele)
  ar1.count(ele) == ar2.count(ele)
end

a1 = [1,4,4,4,5,6]
a2 = [4,4,4]
puts same_amounts?(a1,a2,4)   #true

#1


1  

You could use each_cons to break a1 into multiple chunks (i.e. [1,4,4], [4,4,4], [4,4,5], [4,5,6]). Then you could see if any of those chunks matches a2.

您可以使用each_cons将a1分成多个块(即[1,4,4],[4,4,4],[4,4,5],[4,5,6])。然后你可以看到这些块中是否有任何一个匹配a2。

a1 = [1,4,4,4,5,6]
a2 = [4,4,4]

a1.each_cons(3).include?(a2)
# => true

a1 = [1,4,5,6,4,4]
a1.each_cons(3).include?(a2)
# => false

#2


1  

>> a1 = [1,4,4,4,5,6]
>> a2 = [4,4,4]
>> a1.count(4) == 3 # => true
>> a1.count(4) == a2.count(4) # => true

#3


0  

If you run Enumerable#find_all on an array, it will return an array of all found elements.

如果在数组上运行Enumerable#find_all,它将返回所有找到的元素的数组。

For this particular problem, as falsetru answered, Enumerable#count is much easier and more readable.

对于这个特殊问题,正如falsetru回答的那样,Enumerable #count更容易,更易读。

Note: That will also return true if both arrays have 0 of an element:

注意:如果两个数组都有0个元素,那么它也将返回true:

def same_amounts?(ar1, ar2, ele)
  ar1.count(ele) == ar2.count(ele)
end

a1 = [1,4,4,4,5,6]
a2 = [4,4,4]
puts same_amounts?(a1,a2,4)   #true