Home > Enterprise >  More elegant way of referencing non-diagonal neighbours in a 2D array?
More elegant way of referencing non-diagonal neighbours in a 2D array?

Time:09-19

I was looking over my old code and wanted to make it look more "elegant". Basically overly complicated but looks cooler. I was wondering if anyone could help! Assuming I want to add the 4 neighbours of a given index (x, y) in a 2D array arr, to an new array n, I started with this:

n.add( arr[x][y-1] );
n.add( arr[x][y 1] );
n.add( arr[x-1][y] );
n.add( arr[x 1][y] );

With a bit of googling, this was probably the best answer I managed to find. I tidied it up a little to get this:

for (int i = x-1; i <= x 1; i  ) {
    for (int j = y-1; j <= y 1; j  ) {
        if(!((i == x) && (j == y))) {
            n.add( arr[i][j] );
        }
    }
}

With a bit of tweaking I ended up with this:

for (int i = -1; i <= 1; i  ) {
    for (int j = -1; j <= 1; j  ) {
        if(Math.abs(i) == Math.abs(j)) continue;
        n.add( arr[x i][y j] );
    }
}

How much further can you go with this? I was thinking there may be a way to simplify the if statement with some math logic but I'm not smart enough to think of anything. Help/thoughts would be appreciated!

CodePudding user response:

Note that you make 9 iterations, while only 4 are useful.

If this part of code really needs to be changed, it is possible to store shifts in array and use them. Pseudocode:

yxs = {{0,1},{1,0},{0,-1},{-1,0}}

for (int i = 0; i < 4; i  ) 
    n.add( arr[x yxs[i][0]][y yxs[i][1]]);
  • Related