Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding valid neighbors in 2D array

Tags:

java

arrays

2d

So, I have a 4x4 2D array (it will always be these dimensions). Starting with a location on the array, some row and column, I want to find all of its valid neighbors. So far, I have a really clunky implementation.

//add row
    if ( !((row + 1) > 3)) {
        //do stuff
    }
    //sub row
    if ( !((row - 1) < 0)) {
        //do stuff
    }
    //add col
    if ( !((col + 1) > 3)) {
        //do stuff
    }
    //sub col
    if ( !((col - 1) < 0)) {
        //do stuff
    }
... and so on

This is brutal. I feel like I do not need to check every single neighbor when I start by knowing the location of the element. Any ideas?

like image 602
rhl13 Avatar asked Sep 20 '25 12:09

rhl13


1 Answers

Unfortunately by writing code you are telling a computer what to do and the computer doesn't know anything more than what you tell it.

You can automate this kind of thing a little with nonstandard loop logic though I guess:

for (int coff = -1; coff < 3; coff += 2) {
    for (int roff = -1; roff < 3; roff += 2) {

        if (    col + coff >= 0 &&
                col + coff < array.length &&
                row + roff >= 0 &&
                row + roff < array[row].length) {

            // do stuff with array[col + coff][row + roff]

        }
    }
}

That loop structure will flip the column and row offset from -1 to 1 and then break when they become 3 on the 3rd iteration.

But note that in your code, checking against !(stuff) > 4 will give you an ArrayIndexOutOfBounds exception because remember the last index is 4 - 1.

like image 145
Radiodef Avatar answered Sep 23 '25 00:09

Radiodef