We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Does anyone know how to remove arrays in one array from another, without using ArrayList?
As an example:
int[] set01 = {1, 2, 3, 4, 5, 6};
int[] set02 = {1, 2};
int[] set03;
//function to remove set02 from set01, yielding set03 = {3, 4, 5, 6}
Answers
You could write your own function to do it.
Look at each item in set01.
For each item, look at each item in set02.
Compare them. Did you find this item in set02?
If you didn't find it in set02, add it to set03.
Thansk TfGuy44, The problem is that this is pretty straightforward when 'set02' has only 1 element to compare, but if there are multiple values to check against, a nested loop wouldn't work (as far as I can manage)
If you are trying to use arrays like sets and do set operations on them, and if you aren't particularly attached to vanilla Processing, then one approach is adding a Java Set to your Processing sketch - the interface already has a
removeAll()
method. It also hastoArray()
if you need your set to become an array in other parts of your code.https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#removeAll(java.util.Collection)
Of course, if you want to implement it yourself without using Collections, that is fine too!
Besides using Java's Collection::removeAll() as @jeremydouglass has suggested:
https://Docs.Oracle.com/javase/10/docs/api/java/util/Collection.html#removeAll(java.util.Collection)
We can also rely on Processing's IntList: https://Processing.org/reference/IntList.html
It's got the "hidden" method removeValues():
http://Processing.GitHub.io/processing-javadocs/everything/processing/data/IntList.html#removeValues-int-
And then call its method array() in order to
return
the result as anint[]
:https://Processing.org/reference/IntList_array_.html
whoa, never even heard of removeValues()! You've done it again GoToLoop, thanks, this is EXACTLY the kind of thing I was looking for! Thanks as well Jeremy... I should eventually get to using java.util.*... (too scared!)
There are many ways to do this in Processing.
Another option is to use HashMap as described in the reference, but only use the keys -- for instance, adapt the standard reference example to <Integer, Boolean>.
Note that the reference example includes a java.util import and points straight to the Java docs.
Notice also that the example already uses one part of the set interfaces to HashMap --
entrySet()
. There is also.keySet()
for a set interface to just the keys.If you don't want to use both keys and values -- just a set of things -- an even easier interface is a HashSet, which does this for you. HashSet doesn't have a page in the Processing reference, but it is just as simple to use as HashMap, and you can work with it in the same way.
Here are some simple examples of working with a HashSet in Processing(Java):
Output: