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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With