Reputation: 332
public static int countNeighbors(boolean[][] BB, int r, int c) {
int countalive = 0;
for (int i = r -1;i<=r+1; i++) {
for (int j = c -1; j<c+1;j++) {
if (BB[i][j]) {
countalive++;
}
}
}
return countalive;
}
Matrix being read.
oooooooo
o###oooo
o####o#o
ooo##o#o
o#o#o##o
oooooooo
I noticed something wrong so I printed out this portion of the code. When ran with specifications
countNeighbors(myNewMatrix,1,1)
I get the returned value of 2, when it should in face be 3.
It is counting the number of tiles that are True(#) around it.
This is for a "game of life" assignment.
Upvotes: 1
Views: 99
Reputation: 178303
There are 3 neighbors of (1,1) at (1,2), (2,1), and (2,2). Your code is wrong on 2 accounts:
if
to avoid counting the (r,c) location itself.j
for
loop, before it gets to c + 1
. This makes the count 2 too low (missing 2 matches). Change the condition to j<=c+1
, to be consistent with the i
for
loop condition.The combined effects of the two errors (+1 and -2) explain why your count is low by 1
.
Upvotes: 3