Never been to DZone Snippets before?

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

Full intersection between 2 arrays (See related posts)

// 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 on this post

gregory144 posts on Jun 06, 2006 at 17:42
Or:
class Array
	def real_intersection(arr2)
		(self & arr2).uniq
	end
end
gaspode posts on Jun 06, 2006 at 20:31
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.

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts