Reputation: 1398
In the following code, I am trying to get a Set
of circular primes up to maxPlusOne
.
Set<Integer> primes = getPrimes(maxPlusOne); //Returns a set of all primes up to maxPlusOne ont including it
Set<Integer> circularPrimes = new HashSet<>();
Iterator<Integer> it = primes.iterator();
while(it.hasNext()) {
Set<Integer> perms = getAllRotations(it.next()); //Returns all rotations of an integer 123 => {123, 231, 312}
if(primes.containsAll(perms)) {
circularPrimes.addAll(perms);
// Here I want to do something to the effect of removing all elements in perms from primes
}
}
Now inside the if
statement I want to remove all elements in perms
from primes
. This answer shows how to remove one element that the iterator
is pointing to. Is it even possible to remove multiple elements from circularPrimes
in one iteration? If yes, please help.
Upvotes: 0
Views: 244
Reputation: 17890
The Iterator allows you to remove only the current element. For your case, you need not remove anything. I believe the reason you would like to remove is to avoid calling circularPrimes
for a number that is a circular prime of a previously encountered number. In that case, you can simply check if the number is already part of the circularPrimes
set - if yes don't call getAllRotations
while(it.hasNext()) {
Integer currentNum = it.next();
if (!circularPrimes.contains(currentNum)) {
Set<Integer> perms = getAllRotations(currentNum);
if(primes.containsAll(perms)) {
circularPrimes.addAll(perms);
}
}
}
Upvotes: 1