题目描述:

  • Task:
  • Given 2 circles c1 and c2, output the number of integer points inside the intersection area between them.
  • Each circle is represented as an array of three elements. The first two elements are the coordinates of the center, the third is the radius.
  • Example:
  • For c1 = [2, 2, 3] and c2 = [0, -1, 3], the output should be 8 (see the picture below)
  • There are 8 integer points inside the intersection area between them:(0,2),(0,1),(1,1),(2,1),(0,0),(1,0),(2,0),(2,-1)
  • Input/Output
  • [input] integer array c1
  • The first circle.
  • -1000 ≤ c1[0] and c1[1](coordinates) ≤ 1000
  • -1600 ≤ c1[2](radius) ≤ 1600
  • [input] integer array c2
  • The second circle.
  • -1000 ≤ c2[0] and c2`
  • [1]`(coordinates) ≤ 1000
  • -1600 ≤ c2[2](radius) ≤ 1600
  • [output] an integer
  • The number of integer points inside the * intersection area between c1 and c2.

解决思路和代码:

  • 找到与较小的那个圆相切的那个矩形:
  • pic
    示例图
  • 代码如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    <script>
    function overlapPoint(c1, c2) {
    let min_x,min_y,max_x,max_y;
    if (c1[2]>c2[2]){
    min_x = c2[0] - c2[2];
    min_y = c2[1] - c2[2];
    max_x = c2[0] + c2[2];
    max_y = c2[1] + c2[2];
    } else {
    min_x = c1[0] - c1[2];
    min_y = c1[1] - c1[2];
    max_x = c1[0] + c1[2];
    max_y = c1[1] + c1[2];
    }
    let num = 0;
    for (var x=min_x;x<=max_x;x++) {
    for (var y=min_y;y<=max_y;y++) {
    if (Math.sqrt((x-c1[0])*(x-c1[0]) + (y-c1[1])*(y-c1[1]))<=c1[2] && Math.sqrt((x-c2[0])*(x-c2[0]) + (y-c2[1])*(y-c2[1]))<=c2[2]) {
    num++;
    }
    }
    }
    return num;
    }
    let c1 = [2, 2, 3], c2 = [0, -1, 3];
    console.log(overlapPoint(c1,c2));
    </script>