How do you scroll the circle of values ​​in a 2d array?

Penetrating through the square of a 2d array is easy, but how do you go about a circular section?

+3
source share
3 answers

The way I did this is to do a double for loop, as if you were doing a loop for a 2d array in normal mode. Inside this loop, however, do a check to see if the array element is within a circle of radius r using the distance formula.

For example, given the 10x10 array and the selected "center" of the array in (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
        }
    }
}

(The code is just pseudo code, not any particular language).

+8
source
+3

I understand that you have something like that

[ ][ ][x][0][ ][ ]
[ ][x][ ][ ][1][ ]
[9][ ][ ][ ][ ][2]
[8][ ][ ][ ][ ][3]
[ ][7][ ][ ][4][ ]
[ ][ ][6][5][ ][ ]

If so, you may need to use some basic trigonometry. I would use a trigger to advance the corner until you get the next value and add them to another array (or add the coordinates [i, j] to the new array), because the steps in the corners will not correspond to even steps.

+1
source

Source: https://habr.com/ru/post/1783349/


All Articles