Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN JAVA!!!! Write a method named intersection ( ) that takes two integer arrays

ID: 3703036 • Letter: I

Question

IN JAVA!!!!

Write a method named intersection( ) that takes two integer arrays (A, B) as arguments.

Initialize an array C with N, -1 values, where N is the length of the A or B array. (Assume A and B are the same length.)

If an integer x, is found in both array A and B, store this integer at the first available index (C[index] equals -1) within array C. Return array C to your main method and then print out its elements.


Test your method on the following arrays:

Test #1

A = [1, 2, 3, 4, 5]

B = [5, 4, 3, 2, 1]

=> C = [1, 2, 3, 4, 5]

Test #2

A = [2, 7, 3, 5, 8]

B = [4, 5, 2, 6, 7]

=> C = [2, 7, 5, -1, -1]

Test #3

[1, 2, 3, 4, 5]

[6, 7, 8, 9, 10]

=> C = [-1, -1, -1, -1, -1]

Explanation / Answer

IntersectionTest.java

import java.util.Arrays;

public class IntersectionTest {

public static void main(String[] args) {

int A[] = {1, 2, 3, 4, 5};

int B[] = {5, 4, 3, 2, 1};

System.out.println(Arrays.toString(intersection(A,B)));

int C[] = {2, 7, 3, 5, 8};

int D[] = {4, 5, 2, 6, 7};

System.out.println(Arrays.toString(intersection(C,D)));

}

public static int[] intersection(int a[], int b[]) {

int c[] = new int[a.length];

int k= 0;

for(int i=0;i<a.length;i++) {

for(int j=0;j<b.length;j++) {

if(a[i]==b[j]) {

c[k++]=a[i];

break;

}

}

}

if(k!=a.length) {

int diff=a.length-k;

for(int i=0;i<diff;i++) {

c[k++]=-1;

}

}

return c;

}

}

Output:

[1, 2, 3, 4, 5]
[2, 7, 5, -1, -1]