Currently try to create the game of life, it outputs all the generations (6) and takes in the user input (or if chosen to do automatically), but the next generation after the initial population is not updating following the game of life rules but rather staying the same as the initial population:
Rules:
- Any live cell with fewer than two live neighbours dies, as if by underpopulation.
- Any live cell with two or three live neighbours lives on to the next generation.
- Any live cell with more than three live neighbours dies, as if by overpopulation.
- Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
Any help in fixing this mistake would be appreciated!
// Produce the next generation
void reproduce(int grid[][m]){
int newGrid[n][m];
for (int i=0; i<n; i ) {
for (int j=0; j<m; j ) {
newGrid[i][j] = grid[i][j]; // Copying old grid to a new grid
}
}
// Applying rules for next generation
for (int i=0; i<n; i ) {
for (int j=0; j<m; j ) {
int cellNeighbours = countNeighbours(grid, i, j);
// Live cell rules
if (cellNeighbours < 2 && grid[i][j] == 1) {
newGrid[i][j] == 0;
}
if (cellNeighbours > 3 && grid[i][j] == 1) {
newGrid[i][j] == 0;
}
if (cellNeighbours == 2 && grid[i][j] == 1) {
newGrid[i][j] == 1;
}
if (cellNeighbours == 3 && grid[i][j] == 1) {
newGrid[i][j] == 1;
}
// Dead cell rules
if (cellNeighbours == 3 && grid[i][j] == 0) {
newGrid[i][j] == 1;
}
}
}
}
CodePudding user response:
As user @cigien points out in their comment, you need to update grid
from newGrid
in reproduce
function, and in addition values in newGrid
are not assigned but tested for equality.
Change the newGrid
updates from ==
to =
in reproduce
function and add
for (int i = 0; i < n; i ) {
for (int j = 0; j < m; j ) {
grid[i][j] = newGrid[i][j];
}
}
at the end of reproduce
function
CodePudding user response:
If you use STL like this you can move the temporary array you created at the end instead of copying.
using Grid = std::array<std::array<int, RowNum>,ColNum>
// using Grid = std::vector<std::vector<int>> // non fixed size grid
// ...
Grid newGrid;
// ... (copy from grid)
// ... (do stuff with newGrid, grid remains unchanged)
grid = std::move(newGrid); // move temporary newGrid to grid, should be faster
// than copying back
Of course there are ways to completely avoid the first copy, however optimization wasn't the topic of the question