Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for operating on 2d array with radius

Tags:

java

trying to think of the best way to handle this problem with my 2d game. I want to be able to specify a coordinate pair (x,y) and a radius value. Given this information, I want to operate on all elements of the gameMap[][].

So if radius = 0:

X

if radius = 1:

xxx
xxx
xxx

if radius = 2:

xxxxx
xxxxx
xxxxx
xxxxx
xxxxx

This is what I have so far, which falls apart if radius > 1

for(int i = 1; i < radius; i++) {
                // right
                setAreaObject(locX+i, locY+i);
                setAreaObject(locX+i, (locY+i)-1);
                setAreaObject(locX+i, locY-i);

                // center
                setAreaObject((locX+i)-1, locY+i);
                setAreaObject((locX+i)-1, (locY+i)-1);
                setAreaObject((locX+i)-1, locY-i);

                // left
                setAreaObject(locX-i, locY+i);
                setAreaObject(locX-i, (locY+i)-1);
                setAreaObject(locX-i, locY-i);
            }

Thanks for any thoughts or ideas

like image 824
RandomUser Avatar asked May 17 '26 04:05

RandomUser


1 Answers

for(int x = locX - radius; x <= locX + radius; x++)
{
    for(int y = locY - radius; y <= locY + radius; y++)
    {
            setAreaObject(x, y);
    }
}

If you want the radius to act in two dimensions, you need to loop in two dimensions. Your code loops in only one, and then manually handles the +/- 1 in the Y direction, which is why it doesn't scale. Walk through the loop manually, one iteration at a time, and write down the calls to setAreaObject manually to better understand the way the loop is being evaluated.

like image 60
Overflowed Avatar answered May 18 '26 17:05

Overflowed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!