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
|
#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( typeof( *next_generation ) ) * _size_x );
for ( unsigned int x = 0; x < _size_x; x++ ) {
next_generation[x] = malloc( sizeof( **next_generation ) * _size_y );
}
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 if ( surrdounding_count == 3)
next_generation[x][y] = 1;
else
next_generation[x][y] = _field[x][y];
}
}
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 = 7;
unsigned const int size_y = 7;
field = malloc( sizeof( *field ) * size_x );
for ( unsigned int x = 0; x < size_x; x++ ) {
field[x] = malloc( sizeof( **field) * size_y );
}
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;
}
}
for (unsigned int gen_cnt = 0; gen_cnt < 10; gen_cnt++) {
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");
}
iterate(field, size_x, size_y);
}
for ( unsigned int x = 0; x < size_x; x++) {
free (field[x]);
}
free(field);
return 0;
}
|