Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you loop through a circle of values in a 2d array?

Looping through a square section of a 2d array is easy but how do you loop through a circular section?

like image 892
Stretch Avatar asked Aug 30 '25 16:08

Stretch


1 Answers

The way I've done this is to do a double for-loop like you would for looping through the 2d array normally. Inside this loop, however, do a check to see if the array element in question is within a circle of radius r using the distance formula.

For example, given a 10x10 array, and a chosen "center" of the array at (x,y):

for i from 0 to 9 {
    for j from 0 to 9 {
        a = i - x
        b = j - y
        if a*a + b*b <= r*r {
            // Do something here
        }
    }
}

(Code is just pseudocode, not any particular language).

like image 154
fizban Avatar answered Sep 02 '25 20:09

fizban