I\'m doing the Conway\'s game of life. I\'m pretty sure I\'m close to finished, but when I run it, I get Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsExcep
When r
is 0
, this one is not valid: old[r - 1][c]
.
Thus you get the exception you posted.
I suggest you simplify it like this.
boolean isValidPosition(int r, int c){
return
0 <= r && r < N &&
0 <= c && c < M;
}
int getNeighboursCount(boolean[][] old, int r, int c){
int neighbors = 0;
for (int i=-1; i<=1; i++){
for (int j=-1; j<=1; j++){
if (i!=0 || j!=0){
if (isValidPosition(r + i, c + j)){
if(old[r + i][c + j])
{
neighbors++;
}
}
}
}
}
return neighbors;
}