I am writing a 2D cellular automata that uses a 16×16 grid of objects. The objects are stored in a multi-dimensional array representing the grid. To calculate the values of the next generation, I need to check the state of the surrounding cells (either on or off). If the cell to be checked is at the edge of the grid, then I’d like to have the method wrap around the grid,
I am doing this using the method below method, but am running into problems using the modulo operator:
// Scan neighbours, find out how many are active
int findNeighbours(int x, int y) {
int count = 0;
for(int i = -1; i<1; i++) {
for(int j = -1; j<1; j++) {
// Grid size is 16
int xPos = (x+i)%gridSize;
int yPos = (y+j)%gridSize;
// Check state
if(grid[xPos][yPos].on == true) {
count++;
}
}
}
return count++;
}
The problem is, that I would expect:
(-1) mod 16 = 15
Instead, I get:
(-1) mod 16 = -1
Resulting in an out of bounds error.
What’s happening here?
You could add the divisor to the dividend until it is positive. Some examples to show why this works:
I think Andreas’s comment explains why Java evaluates the % operator far better than I can, but hopefully this solves your problem.