1

I have two arrays:

array1 = [3, 4, 4, 5, 6, 7, 8, 8]
array2 = [4, 5, 8, 8]

I want to remove those elements of array1, which are found in array2, but only in one instance. The resulting array, array3, must be like this:

array3 = [3, 4, 6, 7]

I tried:

array3 = array1 - array2

but the result was unsatisfactory:

array3 -> [3, 6, 7]
0

2 Answers 2

1

This may not be the most efficient way of doing what you want, but it works:

array1 = [3, 4, 4, 5, 6, 7, 8, 8]
array2 = [4, 5, 8, 8]
array2.each do |item|
    index = array1.index item
    array1.delete_at index if index
end
Sign up to request clarification or add additional context in comments.

1 Comment

An imperative solution is ok because it's simple, but note this is O(n^2) time while the problem is O(n). It can be solved using an auxiliar hash.
0

A non-imperative just to show other ways of doing things. Using Facets (just for convenience to get the histogram), I'd write this. O(n):

require 'facets'

array3 = array1.reduce([array2.frequency, []]) do |(h, output), x|
  if h[x] && h[x] > 0
    [h.update(x => h[x] - 1), output]
  else
    [h, output << x] 
  end
end[1]
#=> [3, 4, 6, 7]

To make the snippet purely functional you would use Hash#merge/Array#+ instead of Hash#update/Array:<<, but due to the nature of these data structures it would be terribly inefficient.

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.