I’m trying to write a method that takes 2 ArrayLists of doubles and returns all the values in set1 that aren’t found in set2. These numbers should be returned in set3. Normally I would just use set.contains but I can only use set.get set.size and set.add. Can anyone point me in the right direction?
For example:
If set1 has the numbers 1,2,3,4,5
and set2 has the numbers 1,7,9,5,3
set3 should only contain 2,4,5
ArrayList<Double> setDiff(ArrayList<Double> set1, ArrayList<Double> set2){
ArrayList<Double> set3 = new ArrayList<Double>();
for(int i = 0; i < set1.size(); i++){
for(int x = 0; x < set2.size(); x++){
if(set1.get(i) != set2.get(x)){
set3.add(set1.get(i));
}
}
}
return set3;
}
Problem is, you are adding the number to
set3based on the first failure. So, if the first element ofset2does not matches the current element ofset1, you are adding it toset3.I suspect that this is your homework, given the restrictions in your toolkit. So, I’ll just give you an idea of how to approach.
You can make use of a
booleanvariable, and toggle it (for e.g. set it tofalse), as soon as you find the current element inset2, and then break out of theinner loop.So, your condition in the inner loop will change from: –
to: –
Then outside the
inner loop, check the status of thatbooleanvariable. And based on the status, you can add or not add the current item toset3. for e.g. If the boolean variable isfalse, that means you found the element inset2, so don’t add it toset3, else add it.You also need to reset the boolean variable at the start of the outer loop each time.