0

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. 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]

Tried many options, including keep_if or keep_at, delete_if or delete_at, slice, map, etc.

Current code:

ary1.keep_if { |x| ary2.include?(x) }
1
  • 1
    You say you wish to verify that ary2 is included in ary1. That requires a true or false answer, but you then say the answer should be [1,1,2,3,5]. That makes no sense. Suppose ary1 = [1] and ary2 = [1,1]. In his case is ary2 "included" in ary1? Please edit your question to clarify what you are asking. Commented Jan 24, 2017 at 21:24

2 Answers 2

3

to verify ary2 is included in ary1

(ary2 - ary1).empty?

should equal [1, 1, 2, 3, 5]

ary2.select { |e| ary1.include?(e) }
Sign up to request clarification or add additional context in comments.

2 Comments

Works great. What if I want to find what is left in ary1 after select has been used. I have tried reject, but it deletes the duplicates as well.
ary1.select { |e| !ary2.include?(e) }
0

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. By "unique" I mean, for example, that if ary2 contains two 1's, ary1 must contains two or more 1's. 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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.