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
- public static int[] IntersectionArray(int[] arr, int[] arr2)
- {
- var result = new HashSet<int>();
- var map = new HashSet<int>();
- foreach (var i in arr)
- // if (!map.Contains(i))
- map.Add(i);
- foreach (var i in arr2)
- if (map.Contains(i) )// && !result.Contains(i))
- result.Add(i);
- return result.ToArray();
- }
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
- int[] a = { 1, 2, 3, 4, 5, 6, 5, 6 };
- int[] b = { 3, 4, 3, 4, 3, 4, 3, 4, };
- var test = Questions.IntersectionArray(a, b);
- foreach (var i in test)
- {
- Console.WriteLine(i);
- }
The results in just {3,4}
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:
ReplyDeletereturn new HashSet<int>(arr).Intersect(arr2).ToArray();