Full intersection between 2 arrays
1 2 class Array 3 def real_intersection(arr2) 4 self_sorted = self.sort 5 target_sorted = arr2.sort 6 intersection= [] 7 jstart=0 8 for i in (0..self_sorted.length-1) 9 for j in (jstart..target_sorted.length-1) 10 if self_sorted[i] == target_sorted[j] 11 jstart = j+1 12 intersection[intersection.length] = self_sorted[i] 13 break 14 end 15 end 16 end 17 return intersection 18 end 19 end
// tests
1 2 require 'test/unit' 3 4 class ArrayIntersectionTests < Test::Unit::TestCase 5 def test_real_array_intersection 6 assert_equal [2], [2, 2, 2, 3, 7, 13, 49] & [2, 2, 2, 5, 11, 107] 7 assert_equal [2, 2, 2], [2, 2, 2, 3, 7, 13, 49].real_intersection([2, 2, 2, 5, 11, 107]) 8 assert_equal ['a', 'c'], ['a', 'b', 'a', 'c'] & ['a', 'c', 'a', 'd'] 9 assert_equal ['a', 'a', 'c'], ['a', 'b', 'a', 'c'].real_intersection(['a', 'c', 'a', 'd']) 10 end 11 end