Mark Martin Mark Martin - 8 days ago 4
Java Question

java - Finding the different element of 2 array

I've tried to print the non-intersection of sets between 2 array A and B. But, I have a problem how to print the elements on A different B.
Here is my sample code:

public class Program_Himpunan_Array {

public static void main(String[] args) {
int jlhElemenA, jlhElemenB;

Scanner sc = new Scanner(System.in);

System.out.print("Enter Number of Elements A : ");
jlhElemenA = sc.nextInt();
int[] arrA = new int [jlhElemenA];
System.out.print("Enter Number of Elements B : ");
jlhElemenB = sc.nextInt();
int[] arrB = new int [jlhElemenB];

boolean[] arrTestA = new boolean[jlhElemenA];
boolean[] arrTestB = new boolean[jlhElemenB];

System.out.print("A = ");
for (int i = 0; i <= arrA.length - 1; i++) {
arrA[i] = sc.nextInt();
}
System.out.print("B = ");
for (int i = 0; i <= arrB.length - 1; i++) {
arrB[i] = sc.nextInt();
}

boolean x = true;
int y = 0;
for (int i = 0; i < arrA.length; i++) {
for (int j = 0; j < arrB.length; j++) {
if (arrA[i] == arrB[j]) {
arrTestA[i] = true;
}else y = arrA[i];
}
}

for (int i = 0; i < arrA.length; i++) {
x = x && arrTestA[i];
}

if (x) {
System.out.println("All the elements of A contained in B.");
}else {
System.out.println("There are elements on A different B.");
System.out.println("The elements of A which is not in B = "); //My Problem
}

}
}



This is that I want make:

Enter Number of Elements A : 4

Enter Number of Elements B : 3

A = 1 2 3 4

B = 1 2 3

There are elements on A different B.

The elements of A which is not in B = 4

Answer

To accomplish that you could use Collections and retainAll method. E.g.:

List<Integer> arrTestA = new ArrayList<>();
List<Integer> arrTestB = new ArrayList<>();

[...]

List<Integer> common = new ArrayList<>(arrTestA);
common.retainAll(arrTestB);

List<Integer> diff = new ArrayList<>();
for(Integer element : arrTestA) 
    if(!common.contains(element))
        diff.add(element);

[here you print out elements of diff as The elements of A which is not in B]

ETA: Non Collection attempt:

int[] arr1 = { 1, 11, 5, 9, 4, 3, 4, 8 };
int[] arr2 = { 1, 7, 5, 3, 4, 8 };

Arrays.sort(arr1);
Arrays.sort(arr2);

for (int i : arr1) {
    boolean contains = false;
    for (int j : arr2) {
        if (i == j) {
            contains = true;
            break;
        }
    }
    if (!contains)
        System.out.println("Arr2 doesn't contain number: " + i);
}

...or the loop can look like this:

outer: for (int i : arr1) {
    for (int j : arr2) {
        if (i == j) {
            continue outer;
        }
    }
    System.out.println("Arr2 doesn't contain number: " + i);
}

This is only one way method, but hope you see the point.

ETA2: In my approach, in fact, these Arrays don't have to be sorted. You can simply delete lines of code that are responsible for sorting.