In my latest assignment I am supposed to find the intersection between two integer arrays using recursion and no loops (probably also no specialized methods but it didn't specify).
Input Arrays
[1, 4, 4, 5, 8, 19, 23, 42, 73]
[1, 4, 5, 9, 17, 21, 42, 73]
Expected Output (Intersection Array)
[1, 4, 4, 5, 42, 73]
What I have so far is this:
public static int[] arrayIntersection(int[] a, int[] b) {
int [] result = new int[0];
//System.out.println("a.length: " + a.length + "\nb.length: " + b.length + "\n\n");
if (a.length > 1) {
int[] temp = arrayIntersection(shorten(a), b);
result = append(result, temp);
}
if (b.length > 1) {
int[] temp = arrayIntersection(a, shorten(b));
result = append(result, temp);
}
if(a[a.length - 1] == b[b.length - 1]) result = append(result, a[a.length - 1]);
return result;
}
public static int[] sortedArrayIntersection(int[] a, int[] b) {
return new int[0]; // b)
}
public static int[] append(int[] a, int[]b) {
int[] appended = a;
if (b.length > 0) {
appended = Arrays.copyOf(a, a.length + 1);
appended[appended.length - 1] = b[b.length - 1];
if (b.length > 1) appended = append(appended, shorten(b));
}
return appended;
}
public static int[] append(int[] a, int b) {
int[] appended = a;
appended = Arrays.copyOf(a, a.length + 1);
appended[appended.length - 1] = b;
return appended;
}
public static int[] shorten(int[] a) {
return Arrays.copyOf(a, a.length-1);
}
But this checks the same pairs multiple times and so produces an output that is way too long.
Help me Stack Overflow you're my only hope.