Full intersection between 2 arrays
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