Skip to content

Instantly share code, notes, and snippets.

@0guzhan
Created April 20, 2017 11:32
Show Gist options
  • Save 0guzhan/f6a5c2ad10583fae2b01972e5f209344 to your computer and use it in GitHub Desktop.
Save 0guzhan/f6a5c2ad10583fae2b01972e5f209344 to your computer and use it in GitHub Desktop.
Area of Intersection of Circles; given by coordinates and diameters
/**
* calculates area of intersections of circles
*
* @param x1,y1,r1 first circle
* @param x2,y2,r2 second circle
*/
public double solution(int x1, int y1, int r1, int x2, int y2, int r2) {
double sR1 = power(r1, 2);
double sR2 = power(r2, 2);
double d = distance(x1, y1, x2, y2);
if (r1 == 0 || r2 == 0) {
return 0.0D;
} else if (d > r1 + r2) {
return 0.0D;
} else if (d == 0) {
if (r1 >= r2) {
return Math.PI * sR1;
} else {
return Math.PI * sR2;
}
} else if (d <= Math.abs(r1 - r2) && r1 >= r2) {
return Math.PI * sR1;
} else if (d <= Math.abs(r1 - r2) && r1 < r2) {
return Math.PI * sR2;
} else {
double phi = (Math.acos((sR1 + (d * d) - sR2) / (2 * r1 * d))) * 2;
double theta = (Math.acos((sR2 + (d * d) - sR1) / (2 * r2 * d))) * 2;
double area1 = 0.5 * theta * sR2 - 0.5 * sR2 * Math.sin(theta);
double area2 = 0.5 * phi * sR1 - 0.5 * sR1 * Math.sin(phi);
return area1 + area2;
}
}
private double power(int base, int power) {
if (power <= 0) {
return 1;
} else if (power == 1) {
return base;
} else {
return base * power(base, power - 1);
}
}
private double distance(int x1, int y1, int x2, int y2) {
long xD = x1 - x2;
long yD = y1 - y2;
return Math.sqrt(xD * xD + yD * yD);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment