Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you subtract one array of chars from another in Java?

Tags:

java

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

like image 642
mjd2 Avatar asked Jun 25 '13 12:06

mjd2


People also ask

Can we subtract two characters in Java?

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.

How do you subtract two arrays of elements?

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.

What happens if we subtract two characters in Java?

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!

How do you subtract all the elements in an array?

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.


1 Answers

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.

like image 124
Russell Uhl Avatar answered Sep 28 '22 05:09

Russell Uhl