-
Notifications
You must be signed in to change notification settings - Fork 178
/
program-for-conways-game-of-life
115 lines (101 loc) · 2.1 KB
/
program-for-conways-game-of-life
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
#include <stdio.h>
#include <stdlib.h>
//change row and column value to set the canvas size
int row = 5;
int col = 4;
//creates row boundary
int row_line(){
printf("\n");
for(int i=0; i<col; i++){printf(" -----");}
printf("\n");
}
//returns the count of alive neighbours
int count_live_neighbour_cell(int a[row][col], int r, int c){
int i, j, count=0;
for(i=r-1; i<=r+1; i++){
for(j=c-1;j<=c+1;j++){
if((i==r && j==c) || (i<0 || j<0) || (i>=row || j>=col)){
continue;
}
if(a[i][j]==1){
count++;
}
}
}
return count;
}
int main(){
int a[row][col], b[row][col];
int i,j;
int neighbour_live_cell;
//generate matrix canvas with random values (live and dead cells)
for(i=0; i<row; i++){
for(j=0;j<col;j++){
a[i][j] = rand() % 2;
}
}
//print array matrix
printf("Initial Stage:");
row_line();
for(i=0; i<row; i++){
printf(":");
for(j=0;j<col;j++){
printf(" %d :",a[i][j]);
}
row_line();
}
//next canvas values based on live neighbour count
for(i=0; i<row; i++){
for(j=0;j<col;j++){
neighbour_live_cell = count_live_neighbour_cell(a,i,j);
if(a[i][j]==1 && (neighbour_live_cell==2 || neighbour_live_cell==3)){
b[i][j]=1;
}
else if(a[i][j]==0 && neighbour_live_cell==3){
b[i][j]=1;
}
else{
b[i][j]=0;
}
}
}
//print next generation
printf("\nNext Generation:");
row_line(row);
for(i=0; i<row; i++){
printf(":");
for(j=0;j<col;j++){
printf(" %d :",b[i][j]);
}
row_line(row);
}
return 0;
}
/*
###################################### OUTPUT ####################################
Initial Stage:
----- ----- ----- -----
: 1 : 1 : 0 : 0 :
----- ----- ----- -----
: 1 : 0 : 0 : 0 :
----- ----- ----- -----
: 0 : 0 : 1 : 1 :
----- ----- ----- -----
: 1 : 1 : 1 : 1 :
----- ----- ----- -----
: 1 : 0 : 1 : 0 :
----- ----- ----- -----
Next Generation:
----- ----- ----- -----
: 1 : 1 : 0 : 0 :
----- ----- ----- -----
: 1 : 0 : 1 : 0 :
----- ----- ----- -----
: 1 : 0 : 0 : 1 :
----- ----- ----- -----
: 1 : 0 : 0 : 0 :
----- ----- ----- -----
: 1 : 0 : 1 : 1 :
----- ----- ----- -----
*/
//This code is contributed by adisg25 - Aditya Singh