Finding all the points within a circle in 2D space

前端 未结 7 1784
自闭症患者
自闭症患者 2021-02-13 12:58

I am representing my 2D space (consider a window), where each pixel is shown as a cell in a 2D array. i.e. a 100x100 window is represented by the array of same dimensions.

7条回答
  •  再見小時候
    2021-02-13 14:01

    I know this question has an accepted answer, but I have a far easier solution. The other answers confused me, as I did not know what center, xcenter, ycenter were, and the math behind the functions were left unexplained and I trekked out to discover a mathematical solution of my own.

    My equation is very simple:

    cx is the x point in the center of the circle

    cy is the y point in the center of the circle

    rad is the radius of the circle

    What my equation/function does is calculate the points by calculating each possible point given the radius and it adds and subtracts the offset of cx and cy.

    //Creates an array filled with numbers
    function range(begin, end) {
        for (var i = begin, arr = []; i < end; i++) {
          arr.push(i);
        }
    
        return arr;
    }
    
    function calculateAllPointsInCircle(cx, cy, rad) {
    
       var rang = range(-rad, rad + 1);
       var px = [];
       var py = [];
       var xy = [];
    
       for (var i = 0; i < rang.length; i++) {
         var x = cx + rang[i];
         px.push(x);
    
         for (var l - rang.length - 1; l > 0; l--) {
            var y = cy + rang[l];
            if (!py.indexOf(y)===-1) { py.push(y); }
    
            xy.push(x+','+y);
         }
       }
    
       return {
         x: x,
         y: y,
         xy: xy
       }
    }
    

    The performance is much higher than the other answers: http://jsperf.com/point-in-circle/4 You can check my equation with math, using the equation that will validate if a given point is inside a circle x*x + y*y <= r*r OR x^2 + y^2 <= r^2

    Edit- Super compressed ES6 version:

    function range(begin, end) {
      for (let i = begin; i < end; ++i) {
        yield i;
      }
    }
    
    function calculateAllPointsInCircle(cx, cy, rad) {
        return {
            x: [cx + i for (i of range(-rad, rad + 1))],
            y: [cy + i for (i of range(-rad, rad + 1))]
        };
    }
    

提交回复
热议问题