Let's say I have an array, arrayA = ["a", "b", "c", "d", "e", "f"], and another array, arrayB = ["a", "d", "e"].
I want to subtract arrayB from arrayA to yield the result = ["b", "c", "f"]
This is my setup for each array:
char[] arrayA = new char[7];
for(char c = 'a'; c <= 'f'; ++c) {
arrayA[c - 'a'] = c;
}
char[] arrayB = new char[]{'a','d','e'};
(Please excuse any improper use of symbols and syntax, I'm a Ruby noob trying to learn Java simply from the Oracle tutorials. Thanks!) edit: a word and quotes
Java For Testers You can subtract one range from other and use it as new range. You can achieve this by using two variants of character classes i.e. negation and intersection.
Description. C = A - B subtracts array B from array A by subtracting corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.
When you subtract the characters a from b , then, you get a result of 1 ! With this, the below code block (written in Java, but the concept applies to many other languages) makes sense: In that case, the output would be Wow!
Find the minimum non-zero element in the array, print it and then subtract this number from all the non-zero elements of the array. If all the elements of the array are < 0, just print 0.
The short answer is to convert your arrays to "sets", and then use set operations on them. I'm looking for the proper code for that right now, but you can start by checking out this post: Classical set operations for java.util.Collection
Edit: Luke657 brings up a good point. primitive arrays are weird. So below is the updated code:
Assuming you start with a char array (it would of course be better to start with a set, but oh well):
char[] arrayA = new char[] {'a', 'b', 'c', 'd', 'e', 'f'};
char[] arrayB = new char[] {'a', 'd', 'e'};
Character[] objarrayA = ArrayUtils.toObject(arrayA);
Character[] objarrayB = ArrayUtils.toObject(arrayB);
Set<T> setA = new HashSet(Arrays.asList(objarrayA));
Set<T> setB = new HashSet(Arrays.asList(objarrayB));
setA.removeAll(setB);
Then, to get it back to a char array:
Character[] result;
result = setA.toArray(result);
char[] cresult = ArrayUtils.toPrimitive(result);
I believe this will do what you need. The Arrays.asList()
operation is O(1), so is efficient and not computationally expensive, so don't worry about that extra conversion.
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