summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-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;
+}