Robert Eisele
Engineer, Systems Architect and DBA

Codingame: Disks intersection

Original Problem

Goal

Given centers and radius of two disks, you must determine their intersection area, rounded at a precision of 10^-2.
So if you think the area is 42.3371337, you must output 42.34 and if your answer is 41.78954719, you must print 41.79.

If these disks do not intersect, or intersect in one point, then the area is 0.00 .
Input
Line 1 : x1 y1 r1. x1 and y1 determine the position of the center of the first disk, and r1 its radius
Line 2 : x2 y2 r2. x2 and y2 determine the position of the center of the second disk, and r2 its radius
Output
The intersection area of the disks, rounded at a precision of 10^-2.
Constraints
-1000 < x1,y1,x2,y2 < 1000
1 ⩽ r1,r2 < 1000

Solution

I previously derived the algorithm to calculate the intersection area of two circles. In fact, we can simply copy an implementation of the algorithm over:

function area(A, B) {

  var d = Math.hypot(B.x - A.x, B.y - A.y);

  if (d < A.r + B.r) { // Has intersection?

    var a = A.r * A.r;
    var b = B.r * B.r;

    var x = (a - b + d * d) / (2 * d);
    var y = Math.sqrt(a - x * x);
    
    if (isNaN(y)) {
      // One circle contains the other
      return Math.PI * Math.min(a, b);
    } else {
      // Normal intersection calculation
      return a * Math.asin(y / A.r) + b * Math.asin(y / B.r) - x * y - Math.sqrt(b - a + x * x) * y;
    }
  }
  return 0;
}

All we now have to do is calling the area function with the input data and we are done:

var inputs = readline().split(' ').map(Number);
var A = {x: inputs[0], y: inputs[1], r: inputs[2]};

var inputs = readline().split(' ').map(Number);
var B = {x: inputs[0], y: inputs[1], r: inputs[2]};

print(area(A, B).toFixed(2))

« Back to problem overview