I am trying to do a function that takes a list of circles, and returns only a list of circles that are fully overlapped (one inside another). The problem is that the algorithm is at least O(n²), due to the nested for's in getConcentricCircles function, and taking ages for large datasets. Is there any way to optimize it?
EDIT: I don't know if this would help, but I use the algorithm to detect false positives in iris and pupil detection. If a circle is fully inside another circle, it is likely that that is the pupil and the outside is the iris. They should be concentric, what would simplifiy a lot, but it happens that the pupil in the human eye is not exactly in the center of the iris, that is why I do this.
EDIT 2: I have replaced isCircleInCircle with Peter Lawrey's solution, mine was not correct for some cases
Function to check if a circle is inside a circle:
private static boolean isCircleInCircle(Circle a, Circle b) {
// the circle is inside if the distance between the centre is less than the difference in the radius
double dx = a.getX() - b.getX();
double dy = a.getY() - b.getY();
double radiusDifference = a.getRadius() - b.getRadius();
double centreDistanceSquared = dx*dx + dy*dy; // edited
return radiusDifference * radiusDifference > centreDistanceSquared;
}
Then I check every element of the list with each other, and save only the overlapping circles (and the overlapped circle):
public HashSet<Circle> getConcentricCircles(List<Circle> circleList) {
HashSet<Circle> toReturn = new HashSet<Circle>();
for (Circle circle : circleList) {
for (Circle toCheck : circleList) {
// if the circles are not the same and one is inside another,
if (!toCheck.equals(circle) && isCircleInCircle(circle, toCheck)) {
// add both to the hashset
toReturn.add(circle);
toReturn.add(toCheck);
}
}
}
return toReturn;
}
My first impression to see if a circle is inside another would be to know
This should simplify your logic a lot.
Edit: to improve the complexity,
This will get your list of circles which is surrounded by a larger circle.
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