DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Full Intersection Between 2 Arrays

06.01.2006
| 20031 views |
  • submit to reddit
        // This snippet adds a method to Array to perform a full intersection between 2 arrays. The & method eliminates duplicate objects, this doesn't!

class Array
  def real_intersection(arr2)
    self_sorted = self.sort
    target_sorted = arr2.sort
    intersection= []
    jstart=0
    for i in (0..self_sorted.length-1)
      for j in (jstart..target_sorted.length-1)
        if self_sorted[i] == target_sorted[j]
          jstart = j+1
          intersection[intersection.length] = self_sorted[i]
          break
        end
      end
    end
    return intersection
  end
end

// tests

require 'test/unit'

class ArrayIntersectionTests < Test::Unit::TestCase    
  def test_real_array_intersection
    assert_equal [2], [2, 2, 2, 3, 7, 13, 49] & [2, 2, 2, 5, 11, 107]
    assert_equal [2, 2, 2], [2, 2, 2, 3, 7, 13, 49].real_intersection([2, 2, 2, 5, 11, 107])
    assert_equal ['a', 'c'], ['a', 'b', 'a', 'c'] & ['a', 'c', 'a', 'd']
    assert_equal ['a', 'a', 'c'], ['a', 'b', 'a', 'c'].real_intersection(['a', 'c', 'a', 'd'])
  end
end
    

Comments

Snippets Manager replied on Wed, 2010/09/01 - 10:02am

Isn't that the same as def intersect(array1, array2) array1.collect{ |item| item if array2.include? item }.compact end If you "really" need to sort, then you can sort after compacting, but you can't sort String and FixNum in the same array, for example...

Snippets Manager replied on Thu, 2005/12/15 - 12:26pm

a & b is exactly the same as (a & b).uniq they both only return the set of unique elements in the intersection. What my intersection does is return the intersection, *including* any duplicates.

Snippets Manager replied on Tue, 2006/06/06 - 5:42pm

Or: class Array def real_intersection(arr2) (self & arr2).uniq end end