Reputation: 3
I have a few methods that should run the conway's game of life but in my neighbor count method I don't know how to account for wrap around. I'll put the methods that do this up. Again I mostly just need help with my neighborCount method. I have tested the other methods and they seem to work just fine but when I test the problem method it returns really bogus values.
public class GameOfLife {
private boolean[][] society;
private boolean cell = true;
private boolean empty = false;
public GameOfLife(int rows, int cols) {
// Complete this method.
society = new boolean[rows][cols];
for (int r = 0; r < society.length; r++) {
for (int c = 0; c < society[0].length; c++) {
society[r][c] = empty;
}
}
}
public void growCellAt(int row, int col) {
// Complete this method
society[row][col] = cell;
}
public int neighborCount(int row, int col) {
int count = 0;
for (int r = 0; r < society.length; r++) {
for (int c = 0; c < society[0].length; c++) {
// up and left
if (society[(r - 1 + row) % row][(c - 1 + col) % col] == cell) {
count++;
}
// up
if (society[(r - 1 + row) % row][c] == cell) {
count++;
}
// up and right
if (society[(r - 1 + row) % row][(c + 1 + col) % col] == cell) {
count++;
}
// right
if (society[r][(c + 1 + col) % col] == cell) {
count++;
}
// down and right
if (society[(r + 1 + row) % row][(c + 1 + col) % col] == cell) {
count++;
}
// down
if (society[(r + 1 + row) % row][c]){
count++;
}
// down and left
if (society[(r + 1 + row) % row][(c - 1 + col) % col] == cell) {
count++;
}
// left
if (society[r][(c - 1 + col) % col] == cell) {
count++;
}
}
}
return count;
}
}
Upvotes: 0
Views: 1878
Reputation: 208
You can try using something simpler, like this:
public Cell[] getNeighbours(int i, int j) {
int i2 = i - 1, i3 = i + 1, j2 = j - 1, j3 = j + 1;
if (i2 == -1) i2 = board.length - 1;
if (i3 == (board.length)) i3 = 0;
if (j2 == -1) j2 = board[i].length - 1;
if (j3 == (board[i].length)) j3 = 0;
return new Cell[]{board[i2][j2], board[i2][j], board[i2][j3], board[i][j2], board[i][j3], board[i3][j2], board[i3][j], board[i3][j3]};
}
Upvotes: 0
Reputation: 63481
Your modulo looks to be using the wrong values. ALthough, it's hard to tell because the logic inside that function is a bit odd.
If row
and col
are indices of the cell you want to test (as they seem to be elsewhere), then it's definitely wrong. You need to mod by the actual row length and column length. ie
society[(r - 1 + row) % society.length][(c - 1 + col) % society[0].length]
Beware that modulo of a negative number is generally not a good idea. I don't know if this applies in java or not, but the normal approach is to avoid them. To get around that:
(r + society.length - 1 + row) % society.length
(c + society[0].length - 1 + col) % society[0].length
Upvotes: 2