about summary refs log blame commit diff stats
path: root/cpp/life.cpp
blob: 86e21a1850e7b0f8d5e0700899db85a31c077ff8 (plain) (tree)






































































                                                                                                    
#include <iostream>
#include <vector>
#include <unistd.h>
using namespace std;

// I'll be honest, this smells wrong, but it compiles, so I'm gonna call it good enough for tour

vector<vector<bool> > updateGrid(const vector<vector<bool> >& grid) {
    vector<vector<bool> > new_grid(grid.size(), vector<bool>(grid[0].size(), false));

    for (int i = 0; i < grid.size(); i++) {
        for (int j = 0; j < grid[i].size(); j++) {
            int neighbors = 0;

            for (int x = -1; x <= 1; x++) {
                for (int y = -1; y <= 1; y++) {
                    if (x == 0 && y == 0) {
                        continue;
                    }

                    int new_i = i + x;
                    int new_j = j + y;

                    if (new_i < 0 || new_i >= grid.size() || new_j < 0 || new_j >= grid[i].size()) {
                        continue;
                    }

                    if (grid[new_i][new_j]) {
                        neighbors++;
                    }
                }
            }

            if (grid[i][j]) {
                if (neighbors == 2 || neighbors == 3) {
                    new_grid[i][j] = true;
                }
            } else {
                if (neighbors == 3) {
                    new_grid[i][j] = true;
                }
            }
        }
    }

    return new_grid;
}

int main() {
    vector<vector<bool> > grid(10, vector<bool>(10, false));
    grid[1][2] = true;
    grid[2][3] = true;
    grid[3][1] = true;
    grid[3][2] = true;
    grid[3][3] = true;

    while (true) {
        for (const auto& row : grid) {
            for (bool cell : row) {
                cout << (cell ? "X" : " ");
            }
            cout << endl;
        }
        cout << endl;

        grid = updateGrid(grid);
        usleep(100000);
    }

    return 0;
}