Reputation: 3892
Suppose I have two circles with (x1,y1,r1) and (x2,y2,r2) as their coordinates and radius respectively. With this what is the maximum and minimum distance between them. What I have done till now:
double centreDistance = Math.sqrt(Math.pow((x[i] - x[j]), 2) + Math.pow((x[i] - y[j]), 2));
if (centreDistance >= r[i] + r[j]) {
double maxDistance = centreDistance + (r[i] + r[j]);
double minDistance = centreDistance - (r[i] + r[j]);
} else if (centreDistance == 0) {
double minDistance = Math.abs(r[i] - r[j]);
double maxDistance = Math.abs(r[i] - r[j]);
} else {
int rmax = Math.max(r[i], r[j]);
int rmin = Math.min(r[i], r[j]);
double minDistance = rmax - (centreDistance + rmin);
double maxDistance = rmax + (centreDistance - rmin);
}
Here x,y,r are arrays having x,y coordinates of center of each circle and radius respectively.This gives me the wrong answer.
Upvotes: 1
Views: 1753
Reputation: 8163
The else path is wrong.
This:
double maxDistance = rmax + (centreDistance-rmin);
should be:
double maxDistance = rmax + centreDistance + rmin;
You are also missing the case where the circles intersect. This is the case when
centreDistance < r1+r2 && centredistance + rmin >= rmax
In that case
minDistance = 0
maxDistance = rmax + centreDistance + rmin
centreDistance == 0 is also wrong, it should be maxDistance = r1 + r2
(because you should compare points on opposite side of the center. In any case, it is just a special case of the else path and can be omitted.
The real case are:
centreDistance>=r[i]+r[j] (centres are so far apart the circles don't overlap, or touch in one point)
centreDistance < r1+r2 && centredistance + rmin >= rmax (circles intersect)
centreDistance < r1+r2 && centredistance + rmin < rmax (one circle inside the other)
Upvotes: 2
Reputation: 18838
The problem is rmax
and rmin
are integer. As you return the result of max and min it's rounded to an int
value.
Upvotes: 0
Reputation: 81
in the case where the circle touch, you have to make some adjustments
if (centreDistance >= r[i] + r[j]) {
// the circle dont touch, min and max distance are the closest and most far apart parts of the circles
// code is correct
double maxDistance = centreDistance + (r[i] + r[j]);
double minDistance = centreDistance - (r[i] + r[j]);
} else if (centreDistance == 0) {
// the circle are on top of each other
// check if they have the same radius -> max min dist = 0
// if not max and min distance = Math.abs(r[i] - r[j]);
// code is correct
double minDistance = Math.abs(r[i] - r[j]);
double maxDistance = Math.abs(r[i] - r[j]);
} else {
// the circles touch
// max distance is the same as in case where they dont touch
// and min distance is 0 because they touch
// code has to be adjusted
int rmax = Math.max(r[i], r[j]);
int rmin = Math.min(r[i], r[j]);
double minDistance = rmax - (centreDistance + rmin);
double maxDistance = rmax + (centreDistance - rmin);
}
Upvotes: 0