Reputation: 173
Let's say I have an array N with n values. Let's also say I have another array A with n-1 values. How would I detect which value does not exist in array A. My Java code currently has two nested for loops
for(int j = 0; j < array.length; j++){
for(int k = j; k < n.length; k++){
These search through each value in each array and compares them. So how would I detect if a value that exists in array N does not exist in array A?
P.S It's been awhile since I've used Java so please let me know if there's a better way to search through two arrays.
Upvotes: 0
Views: 3436
Reputation: 1089
int[] n = new int[] {1,2,3,4};
int[] a = new int[] {2,3,4};
Set<Integer> aSet = new HashSet<>();
for (int i = 0; i < a.length; i++) {
aSet.add(a[i]);
}
Set<Integer> valuesNotInA = new HashSet<>();
for (int i = 0; i < n.length; i++) {
if (aSet.add(n[i])) {
valuesNotInA.add(n[i]);
}
}
Upvotes: 0
Reputation: 298
Simply you should check the array of bigger size elements exists in the other one.
int i = 0; // start a global "i" for marking Array N
for(i = 0; i < N.length; i++){
int k = 0; // start a local-global k for marking Array A.
for(k = 0; k < A.length; k++){
if (A[k] == N[i]) {
break;
}
}
// if k reaches to end of the array A then we found the missing num
if (k==A.length) {
break;
}
}
// Still in any case of giving wrong inputs. if i reaches to the end of the Array N then no missing values found.
if (i != N.length)
System.out.println("the number missing is : " + N[i]);
Upvotes: 0
Reputation: 22972
You can achieve this easily with List
,
List<Integer> xList = Arrays.asList(new Integer[]{1,2,3,4});
List<Integer> yList = Arrays.asList(new Integer[]{1,2,3});
List<Integer> missingList = new ArrayList<Integer>(xList);
missingList.removeAll(yList);
System.out.println("Elements are in x but not in y are : "+missingList);
OUTPUT
Elements are in x but not in y are : [4]
Upvotes: 1
Reputation: 2720
You could use a library like Guava to get the difference of two sets, then see which elements are only present in A, or which elements are only present in N.
Upvotes: 0