Im trying to create a method that it´s able to print the difference between two sets of numbers
In this case, I want to make the difference (h1 - h2) or in other words, print all the elements of the array h1 that are not also in h2.
so far this is what i have come up with, and it works only if the numbers of the first set h1 are smaller than the ones of the second set h2, but I want to make it work under any given set.
I would really apreciate any idea that you might have, Thanks ¡
private void metodoDifference(int[] h1, int[] h2, int m, int n) {
int i = 0, j = 0;
ArrayList<Integer> arrayDifference = new ArrayList<>();
while (i < m && j < n) {
if(h1[i] < h2[j]) {
arrayDifference .add(h1[j++]);
i++;}
else if (h2[j] < h1[i]){
arrayDifference .add(h1[j++]);
}
else {
i++;
j++;
}
}
differenceText.setText(arrayDifference .toString());
}
You don't appear to need m or n. I would use ArrayList.removeAll(Collection). Then, assuming you are using Java 8+, you can collect and box your int[](s) in one step. Like,
private void metodoDifference(int[] h1, int[] h2) {
List<Integer> arrayDifference = Arrays.stream(h1).boxed().collect(Collectors.toList());
arrayDifference.removeAll(Arrays.stream(h2).boxed().collect(Collectors.toList()));
differenceText.setText(arrayDifference.toString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With