Repository navigation
Expand file tree
/
Copy path31-IntersectionAndUnion.java
More file actions
77 lines (68 loc) · 2.28 KB
/
Copy path31-IntersectionAndUnion.java
File metadata and controls
77 lines (68 loc) · 2.28 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
73
74
75
76
77
import java.util.Scanner;
class IntersectionAndUnion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] first = readArray(scanner, "first");
int[] second = readArray(scanner, "second");
System.out.print("Intersection: ");
printIntersection(first, second);
System.out.println();
System.out.print("Union: ");
printUnion(first, second);
System.out.println();
scanner.close();
}
private static void printIntersection(int[] first, int[] second) {
boolean found = false;
for (int i = 0; i < first.length; i++) {
if (contains(second, first[i]) && firstIndex(first, first[i]) == i) {
System.out.print(first[i] + " ");
found = true;
}
}
if (!found) {
System.out.print("None");
}
}
private static void printUnion(int[] first, int[] second) {
boolean found = false;
for (int i = 0; i < first.length; i++) {
if (firstIndex(first, first[i]) == i) {
System.out.print(first[i] + " ");
found = true;
}
}
for (int i = 0; i < second.length; i++) {
if (secondIndex(second, second[i]) == i && !contains(first, second[i])) {
System.out.print(second[i] + " ");
found = true;
}
}
if (!found) {
System.out.print("None");
}
}
private static int firstIndex(int[] numbers, int value) {
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == value) {
return i;
}
}
return -1;
}
private static int secondIndex(int[] numbers, int value) {
return firstIndex(numbers, value);
}
private static boolean contains(int[] numbers, int value) {
return firstIndex(numbers, value) != -1;
}
private static int[] readArray(Scanner scanner, String name) {
System.out.print("Enter size of " + name + " array: ");
int size = scanner.nextInt();
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
numbers[i] = scanner.nextInt();
}
return numbers;
}
}