about summary refs log tree commit diff stats
path: root/cpp/life.cpp
blob: 86e21a1850e7b0f8d5e0700899db85a31c077ff8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#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;
}