-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path_04_ArrayQuestions16.cs
50 lines (48 loc) · 1.1 KB
/
_04_ArrayQuestions16.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Linq;
using System.Reflection;
using OurCompany;
/*
16. Implement a routine to receive two arrays of integers (ascending order)
and return an array with the intersection
*/
public class ArrayQuestion16
{
public static void Main(string[] args)
{
int[] a = { 3, 6, 8, 13, 17, 21, 40 };
int[] b = { 1, 3, 5, 17, 60 };
int[] intersection = ArrayIntersection(a, b);
MyArray.Print(a, "Array a");
MyArray.Print(b, "Array b");
MyArray.Print(intersection, "Array intersection");
}
private static int[] ArrayIntersection(int[] a, int[] b)
{
int[] intersection = new int[Math.Min(a.Length, b.Length)];
int ia = 0;
int ib = 0;
int ii = 0;
while (ia < a.Length && ib < b.Length)
{
if (a[ia] == b[ib])
{
intersection[ii] = a[ia];
ia++;
ib++;
ii++;
}
else if (a[ia] < b[ib])
{
ia++;
}
else
{
ib++;
}
}
int[] result = new int[ii]; // Error with there is no intersection
Array.Copy(intersection, 0, result, 0, ii);
return result;
}
}