Java (7 pts) Suppose that you and I are friends on social media, and you want to
ID: 3700716 • Letter: J
Question
Java
(7 pts) Suppose that you and I are friends on social media, and you want to figure out the friends we have in common. One way of doing this would be to treat your friends list as an array and my frends list as another array. Then, the problem of finding our common friends would be solvable by finding the intersection (set of common elements) between those two arrays. Assume that each friend is represented by a unique numerical ID number. Using a person's name directly isn't a good idea, because it's possible for more than one person to have the same name. 2. Within a new class named ArrayIntersection, write a method void intersection(int] al, intl a2) that takes two int arrays of ID numbers as parameters. The method should find and display the intersection between those two arrays. The method should also find and display the count of common elements between the two arrays. You can assume that both arrays contain unique elements - that is, neither array contains duplicate elements within itself. Hint; For each element of al, perform a linear search of a2. Note the void return type - this method does not need to return anything. Just have it print the intersection and the quantity of elements in that intersection. Test your intersection method by calling it from a main method (within the same ArrayIntersection class). You do not need to get any user input -just create your test arrays directly within your main method.Explanation / Answer
public class ArrayIntersection {
void intersection(int[] a1, int[] a2) {
System.out.print("Intersection between these two array is:");
int count = 0;
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
System.out.print(" " + a1[i]);
count++;
break;
}
}
}
System.out.println();
System.out.println("Count of common element is: " + count);
}
public static void main(String[] args) {
ArrayIntersection ai = new ArrayIntersection();
int[] a1 = {1, 2, 4, 5, 7};
int[] a2 = {2, 5, 8, 9};
ai.intersection(a1, a2);
}
}
Sample run
javac ArrayIntersection.java
java ArrayIntersection
Intersection between these two array is: 2 5
Count of common element is: 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.