Created
October 19, 2015 21:35
-
-
Save Manu343726/3db729af111be6870bda to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <utility> | |
#include <algorithm> | |
void update(std::vector<bool>& map, std::size_t rows, std::size_t columns, bool(*rules)(std::size_t, bool)) | |
{ | |
auto at = [](std::size_t row, std::size_t column) | |
{ | |
return row * columns + column; | |
}; | |
static std::vector<bool> next{(rows+1)*(columns+1)}; | |
for(std::size_t i = 1; i < rows - 1; ++i) | |
{ | |
for(std::size_t j = 1; j < columns - 1; ++i) | |
{ | |
std::size_t alive_neighbors = 0; | |
alive_neighbors += map[at(i-1 , j-1)]; | |
alive_neighbors += map[at(i-1 , j )]; | |
alive_neighbors += map[at(i-1 , j+1)]; | |
alive_neighbors += map[at(i , j+1)]; | |
alive_neighbors += map[at(i+1 , j+1)]; | |
alive_neighbors += map[at(i+1 , j )]; | |
alive_neighbors += map[at(i+1 , j-1)]; | |
alive_neighbors += map[at(i , j-1)]; | |
next[at(i,j)] = rules(alive_neighbors, map[at(i,j)]); | |
} | |
} | |
std::swap(map, next); | |
} | |
auto make_rule(std::initializer_list<std::size_t> alive, std::initializer_list<int> dead) | |
{ | |
return [](std::size_t neighbors, bool current) | |
{ | |
if(current) | |
return std::find(alive.begin(), alive.end(), neighbors) != alive.end(); | |
else | |
return std::find(dead.begin(), dead.end(), neighbors) != dead.end(); | |
} | |
} | |
int main(int argc, const char* argv[]) | |
{ | |
assert(argc == 3); | |
const std::size_t rows = argv[1]; | |
const std::size_t columns = argv[2]; | |
std::vector<bool> map{(rows+1)*(columns+1)}; | |
// Some rulesets | |
auto conway_gol = make_rule({2,3},{3}); | |
auto amoebas = make_rule({1,3,5,8},{1,3,5,7}); | |
auto laberinth = make_rule({2,3,4,8},{3,8}); | |
while(true) | |
{ | |
step(map, rows, columns, conway_gol; | |
// Print map, etc | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment