I'm implementing Conway's game of life with a malloc'd array as a grid of 0s and 1s, anywhere with a 0 I print a white background space representing a "dead" cell and anywhere with 1 I print a black background space representing an "alive" cell.
I'm having some trouble with updating the cells on each cycle. My approach was to have a getState() function, which just checks if a grid entry is 0 or 1 and then returns a value correspondingly. I also have a countN() function which goes through the grid, and counts the numbers - accounting for corner, edge and centre cases. I've tested those thoroughly with several examples and they are working how I expect them to, for a given grid coordinate it always returns the correct state & number of alive neighbours.
This is what I've attempted to do (pseudocode):
void updateGrid(int **grid, int r, int c) {
copyGrid = grid;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++) {
alive->getState(grid, i, j)
neighbours->countN(grid, i, j)
if (alive) {
if (neighbour < 2 || neigbour > 3)
copyGrid[i][j] = 0;
else
copyGrid[i][j] = 1;
} else {
if (neighbour == 3)
copyGrid[i][j] = 1;
else
copyGrid[i][j] = 0;
}
}
grid = copyGrid;
printGrid(grid, r, c)
}
There's a simple calling function which just generates an initial grid from an input file, clears the screen and then calls updateGrid() and sleeps after each cycle, until a certain number of cycles. The initial grid is how I expect it to be, the neighbours and alive functions return the correct values but the grid updates incorrectly and the output is quite distorted.
As an example, using 1s and 0s:
Input: Expected Output: Actual Output
0 0 0 0 1 0 0 1 1
1 1 1 0 1 0 1 0 1
0 0 0 0 1 0 0 0 0
Any tips would be greatly appreciated!