HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Game of Life generation procession algorithm

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
algorithmgenerationgameprocessionlife

Problem

I've tried to make Game of Life in console and this is the algorithm I used to generate new generation:

void processGeneration() {
    population = 0;
    int neighbors;
    int tempGrid[ROWS][COLS];
    for(int i = 0; i  3) {
                    tempGrid[i][j] = 0;
                } else {
                    tempGrid[i][j] = 1;
                }
            }
        }
    }
    for(int i = 0; i < ROWS; i++) {
        for(int j = 0; j < COLS; j++) {
            if (grid[i][j] == -1) {
                continue;
            }
            if (tempGrid[i][j] == 1) {
                population++;
            }
            grid[i][j] = tempGrid[i][j];
        }
    }
}


I'm a bit uncertain if what I did was right, so could you check the algorithm? Also, grid is the grid where I save the cells in and I just use tempGrid to change the values and then copy them to the grid.

int countNeighbors(int row, int col) {
    int neighbors = 0;
    for(int i = row - 1; i  -1 && j > -1 && i < ROWS && j < COLS) {
                neighbors += grid[i][j];
            }
        }
    }
    return neighbors;
}

Solution

Your algorithms looks correct, I could not find any obvious mistakes.

On the other hand, I have a suggestion towards the readability of your code:
Use more functions that tell the reader what you're doing right now. For example, instead of saying

if (grid[i][j] == 0) {
    if (neighbors == 3) {
        tempGrid[i][j] = 1;
    } else {
        tempGrid[i][j] = 0;
    }
}


you could write:

int cellIsDead(int x, int y) { return grid[i][j] == 0; }
int hasEnoughNeighboursToComeToLife(int x, int y) { return countNeighbors(x, y) == 3 }
void makeCellComeAlive(int x, int y) { tempGrid[i][j] = 1; }

if (cellisDead(i, j) && hasEnoughNeighboursToComeToLife(i, j)) {
    makeCellComeAlive(i, j);
}


Yes, this takes more time and also probably some global variables (although grid already looks global, so no issue), but it is a) easier to read (see how it almost reads like the rules of the game?) and b) easier to prove to be correct using unit tests. And any decent compiler will inline these function calls at compile time, so no runtime overhead.

Code Snippets

if (grid[i][j] == 0) {
    if (neighbors == 3) {
        tempGrid[i][j] = 1;
    } else {
        tempGrid[i][j] = 0;
    }
}
int cellIsDead(int x, int y) { return grid[i][j] == 0; }
int hasEnoughNeighboursToComeToLife(int x, int y) { return countNeighbors(x, y) == 3 }
void makeCellComeAlive(int x, int y) { tempGrid[i][j] = 1; }


if (cellisDead(i, j) && hasEnoughNeighboursToComeToLife(i, j)) {
    makeCellComeAlive(i, j);
}

Context

StackExchange Code Review Q#61591, answer score: 4

Revisions (0)

No revisions yet.