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.
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
}
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