summaryrefslogtreecommitdiff
path: root/main.c
diff options
context:
space:
mode:
authorGravatar Jonas Gunz <himself@jonasgunz.de> 2020-04-30 22:42:23 +0200
committerGravatar Jonas Gunz <himself@jonasgunz.de> 2020-04-30 22:42:23 +0200
commitac692a11f3e5c6c227acfc2785f824edb1834a32 (patch)
tree2186edad2cbde79ef9b8717672a9b92bae83753b /main.c
downloadgameoflife-ac692a11f3e5c6c227acfc2785f824edb1834a32.tar.gz
initial
Diffstat (limited to 'main.c')
-rw-r--r--main.c86
1 files changed, 86 insertions, 0 deletions
diff --git a/main.c b/main.c
new file mode 100644
index 0000000..fd9c20c
--- /dev/null
+++ b/main.c
@@ -0,0 +1,86 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+unsigned int calculate_area(int **_field, unsigned int _size_x, unsigned int _size_y, unsigned int _x, unsigned int _y) {
+ unsigned const int min_x = _x == 0 ? 0 : _x - 1;
+ unsigned const int max_x = _x == _size_x - 1 ? _x : _x + 1;
+
+ unsigned const int min_y = _y == 0 ? 0 : _y - 1;
+ unsigned const int max_y = _y == _size_y - 1 ? _y : _y + 1;
+
+ unsigned int area_sum = 0;
+
+ for ( unsigned int x = min_x; x <= max_x; x++ ) {
+ for ( unsigned int y = min_y; y <= max_y; y++ ) {
+ area_sum += _field[x][y];
+ }
+ }
+
+ area_sum -= _field[_x][_y];
+
+ return area_sum;
+}
+
+void iterate(int **_field, unsigned int _size_x, unsigned int _size_y) {
+ int **next_generation = NULL;
+
+ next_generation = malloc( sizeof( *next_generation ) * _size_x );
+ for ( unsigned int x = 0; x < _size_x; x++ ) {
+ next_generation[x] = malloc( sizeof( **next_generation ) );
+ }
+
+ for (unsigned int x = 0; x < _size_x; x++) {
+ for (unsigned int y = 0; y < _size_y; y++) {
+ unsigned int surrdounding_count = calculate_area(_field, _size_x, _size_y, x, y);
+ if (surrdounding_count < 2 || surrdounding_count > 3)
+ next_generation[x][y] = 0;
+ else
+ next_generation[x][y] = 1;
+ }
+ }
+
+ for (unsigned int x = 0; x < _size_x; x++) {
+ for (unsigned int y = 0; y < _size_y; y++) {
+ _field[x][y] = next_generation[x][y];
+ }
+ }
+
+ for ( unsigned int x = 0; x < _size_x; x++ ) {
+ free (next_generation[x]);
+ }
+ free(next_generation);
+}
+
+int main(void) {
+
+ int **field = NULL;
+
+ unsigned const int size_x = 3;
+ unsigned const int size_y = 3;
+
+ field = malloc( sizeof( *field ) * size_x );
+ for ( unsigned int x = 0; x < size_x; x++ ) {
+ field[x] = malloc( sizeof( **field ) );
+ }
+
+ for (unsigned int x = 0; x < size_x; x++) {
+ for (unsigned int y = 0; y < size_y; y++) {
+ field[x][y] = x == y ? 1 : 0;
+ }
+ }
+ unsigned int gen_cnt = 0;
+ while ( 1 ) {
+ printf("\n\nGeneration %i\n", gen_cnt);
+ for (unsigned int x = 0; x < size_x; x++) {
+ for (unsigned int y = 0; y < size_y; y++) {
+ printf("%c", field[x][y] ? 'X' : ' ');
+ }
+ printf("\n");
+ }
+
+ gen_cnt ++;
+ iterate(field, size_x, size_y);
+ }
+
+ return 0;
+}