Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming Logic: How to Check for Neighbors in a Grid?

Tags:

java

grid

I'm having a lot of trouble trying to think of a logical way to check for neighbors in a "grid"-based programming project for class.

The main problem I'm having is thinking of a way to effectively check whether its on the sides so that I don't get an index out of bounds error.

EDIT: I forgot to mention that I'm using a 2-dimensional array.

like image 398
Devoted Avatar asked Oct 21 '25 07:10

Devoted


1 Answers

Here's a simple way of getting a neighbour position avoiding worrying about the sides:

int leftX = (x - 1 + width) % width;
int rightX = (x + 1) % width;
int aboveY = (y - 1 + height) % height;
int belowY = (y + 1) % height;

It's possibly not the most efficient way of doing it, but it keeps each calculation to a single, simple expression. That's assuming you want wrap-around, of course. If you don't, you'll have to do things conditionally:

if (x > 0)
{
    // Use x - 1
}
if (x < width - 1)
{
    // Use x + 1
}
like image 148
Jon Skeet Avatar answered Oct 23 '25 20:10

Jon Skeet