Finding all the points within a circle in 2D space

前端 未结 7 1778
自闭症患者
自闭症患者 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 13:50

    Will it serve my purpose?

    For your 100x100, yes.

    Can I make it faster?

    Yes. For example, you can:

    • Check only 1 quadrant and get other points because of symmetry.
    • Skip the square root when calculating the distance.

    Code:

    for (x = xCenter - radius ; x <= xCenter; x++)
    {
        for (y = yCenter - radius ; y <= yCenter; y++)
        {
            // we don't have to take the square root, it's slow
            if ((x - xCenter)*(x - xCenter) + (y - yCenter)*(y - yCenter) <= r*r) 
            {
                xSym = xCenter - (x - xCenter);
                ySym = yCenter - (y - yCenter);
                // (x, y), (x, ySym), (xSym , y), (xSym, ySym) are in the circle
            }
        }
    }
    

    That's about 4x speed up.

    JS tests for solutions presented here. Symmetry is the fastest on my computer. Trigonometry presented by Niet the Dark Absol is very clever, but it involves expensive mathematical functions like sin and acos, which have a negative impact on performance.

提交回复
热议问题