-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayIntersection.java
More file actions
72 lines (59 loc) · 2 KB
/
ArrayIntersection.java
File metadata and controls
72 lines (59 loc) · 2 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Program to find the intersection of two arrays:
* Write a Java program to find the intersection of two arrays and return a new array containing only the common elements.
* Assume no duplictes in input arrays
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ArrayIntersection {
public static List<Integer> intersection(int[] a, int[] b)
{
ArrayList<Integer> result = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
result.add(a[i]); // Store the intersection element
break; // Once an intersection is found, move to the next element in 'a'
}
}
}
return result;
}
public static void printList(List<Integer> list) {
if(list.size()==0)
{
System.out.println("No common elements found in the two input arrays: ");
}
else
{
for (int num : list) {
System.out.print(num + " ");
}
}
System.out.println();
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the first array: ");
int n = sc.nextInt();
System.out.println("Enter the size of the second array: ");
int m = sc.nextInt();
int[] inputArray_1 = new int[n];
System.out.println("Enter the "+ n + " array elements: ");
for(int i=0; i<n; i++)
{
inputArray_1[i] = sc.nextInt();
}
int[] inputArray_2 = new int[m];
System.out.println("Enter the "+ m + " array elements: ");
for(int i=0; i<m; i++)
{
inputArray_2[i] = sc.nextInt();
}
System.out.println("Array intersection of these: ");
printList(intersection(inputArray_1, inputArray_2));
sc.close();
}
}