简体   繁体   English

Ruby数组比较而不删除重复项

[英]Ruby Array Comparison Without Deleting Duplicates

I have seen many questions regarding this, but not one that addresses the issue of duplicate values. 我看到了很多与此有关的问题,但没有一个解决重复值的问题。

Below are two arrays. 以下是两个数组。 I need to verify ary2 is included in ary1 regardless of the extra duplicates. 我需要验证ary2是否包含在ary1而不管是否有多余的重复项。 Also needs to work regardless if the arrays are holding numbers or characters. 无论数组包含数字还是字符,也都需要工作。

ary1 = [1, 1, 1, 2, 2, 3, 4, 5, 6]
ary2 = [1, 1, 2, 3, 5]

Should equal [1, 1, 2, 3, 5] , my code equals [1, 1, 1, 2, 2, 3, 5] 应该等于[1, 1, 2, 3, 5] 1、1、2、3、5 [1, 1, 2, 3, 5] ,我的代码等于[1, 1, 1, 2, 2, 3, 5] 1、1、1、2、2、3、5 [1, 1, 1, 2, 2, 3, 5]

Tried many options, including keep_if or keep_at , delete_if or delete_at , slice , map , etc. 尝试了许多选项,包括keep_ifkeep_atdelete_ifdelete_atslicemap等。

Current code: 当前代码:

ary1.keep_if { |x| ary2.include?(x) }

to verify ary2 is included in ary1 验证ary2是否包含在ary1中

(ary2 - ary1).empty?

should equal [1, 1, 2, 3, 5] 应该等于[1, 1, 2, 3, 5]

ary2.select { |e| ary1.include?(e) }

Reading between the lines, I'm assuming that " ary2 is included in ary1 " means that, for each element of ary2 , there a unique element of ary1 with the same value. 在两行之间阅读时,我假设“ ary2 包含ary1 ”意味着对于ary2每个元素, ary2的唯一元素ary1具有相同的值。 By "unique" I mean, for example, that if ary2 contains two 1 's, ary1 must contains two or more 1 's. 例如,“唯一”是指如果ary2包含两个1 ,则ary1必须包含两个或多个1 If this interpretation of the question is incorrect there is no reason to read further. 如果对问题的这种解释不正确,则没有理由进一步阅读。

If my assumption is correct, we could construct a method (with arguments ary1 and ary2 ) that returns true or false , but if there is a match ( true ) it might be more useful to return the elements of ary1 that are "left over" after elements of ary1 have been matched to the elements of ayr2 . 如果我的假设是正确的,我们可以构造一个返回truefalse的方法(带有ary1ary2参数),但是如果存在匹配项( true ),则返回“剩余”的ary1元素可能会更有用。在ary1的元素与ayr2的元素匹配ayr2

def ary2_included_in_ary1?(ary1, ary2)
  ary1_cpy = ary1.dup
  ary2.all? do |n|
    idx = ary1_cpy.index n
    return false if idx.nil?
    ary1_cpy.delete_at(idx)
  end
  ary1_cpy
end

ary1 = [1, 1, 1, 2, 2, 3, 4, 5, 6]

ary2 = [1, 1, 2, 3, 5]
ary2_included_in_ary1?(ary1, ary2)
  #=> [1, 2, 4, 6]

ary2 = [1, 1, 2, 3, 7]
ary2_included_in_ary1?(ary1, ary2)
#=> false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM