-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCell_Auto.cpp
126 lines (104 loc) · 2.77 KB
/
Cell_Auto.cpp
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <random>
#include <chrono>
using namespace std;
// UNCHANGEABLE CONSTANTS
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
vector<int> offsets = {1, 0, -1, -1, 1, -1, 0, 1, 1};
// CHANGEABLE CONSTANTS
int STATE_AMOUNT = 2;
int N = 5;
int M = 5;
// TYPES
#define cord pair<int,int>
// SIMPLE FUNCTIONS
int getRandom(int from, int to){
return uniform_int_distribution<int>(from,to)(rng);
}
// GENERAL FUNCTIONS
vector<cord> getNeighbors(cord from){
vector<cord> res;
for(int i = 0; i < 8; i++){
int nx = (from.first+offsets[i]+N)%N;
int ny = (from.second+offsets[i+1]+M)%M;
res.push_back({nx,ny});
}
return res;
}
int getStateByRules(cord from, vector<vector<int>>& grid){
vector<cord> neighbors = getNeighbors(from);
int liveAm = 0;
for(int i = 0; i < neighbors.size(); i++) liveAm += grid[neighbors[i].first][neighbors[i].second];
if(grid[from.first][from.second]) return liveAm == 2 || liveAm == 3;
else return liveAm == 3;
}
void getNextIteration(vector<vector<int>>& before, vector<vector<int>>& after){
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
after[i][j] = getStateByRules({i,j}, before);
}
}
}
// DISPLAY
char stateToCharacter(int state){
if(state == 1) return '#';
return ' ';
}
int characterToState(char c){
if(c == '#') return 1;
return 0;
}
void consoleDisplay(vector<vector<int>>& grid){
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
cout << stateToCharacter(grid[i][j]);
}
cout << endl;
}
}
// HELPER
void setUpGrid(vector<string>& setup, vector<vector<int>>& grid){
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
grid[i][j] = characterToState(setup[i][j]);
}
}
}
void copyGrid(vector<vector<int>>& to, vector<vector<int>>& from){
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
to[i][j] = from[i][j];
}
}
}
void setUpGridRandom(vector<vector<int>>& grid){
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
// Depends on rule variant
grid[i][j] = getRandom(0,STATE_AMOUNT-1);
}
}
}
int main(){
vector<vector<int>> before(N, vector<int>(M));
vector<vector<int>> after(N, vector<int>(M));
vector<string> initialSetup = {
"# ",
" # ",
" ## ",
" # ",
" "
};
setUpGrid(initialSetup, before);
while(true){
getNextIteration(before,after);
consoleDisplay(after);
_sleep(1000);
getNextIteration(after,before);
consoleDisplay(before);
_sleep(1000);
}
return 0;
}