Tech Qu: Intersect two arrays

Write the code to find the intersection of two arrays, a,b.

 

The code can be very simple (or horribly complex) from the right perspective:

Code Snippet
  1. public static int[] IntersectionArray(int[] arr, int[] arr2)
  2. {
  3.   var result = new HashSet<int>();
  4.   var map = new HashSet<int>();
  5.   foreach (var i in arr)
  6.   //  if (!map.Contains(i))
  7.       map.Add(i);
  8.   foreach (var i in arr2)
  9.     if (map.Contains(i) )// && !result.Contains(i))
  10.       result.Add(i);
  11.   return result.ToArray();
  12. }

 

I have included some unneeded condition tests as comments above (HashSet does not retain duplicates and it is assumed that an explicit test would be more expensive then letting the hashset do it itself).

 

Unit testing is trivial

Code Snippet
  1. int[] a = { 1, 2, 3, 4, 5, 6, 5, 6 };
  2. int[] b = { 3, 4, 3, 4, 3, 4, 3, 4, };
  3. var test = Questions.IntersectionArray(a, b);
  4. foreach (var i in test)
  5. {
  6.   Console.WriteLine(i);
  7. }

The results in just {3,4}

Comments

  1. If you're going to use HashSet to solve the problem, it seems like you should also use the methods it provides. IntersectionArray can be rewritten as one line:

    return new HashSet<int>(arr).Intersect(arr2).ToArray();

    ReplyDelete

Post a Comment

Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape