Skip to content

Commit

Permalink
Merge pull request #122 from AnishKr91620/patch-1
Browse files Browse the repository at this point in the history
Create program-for-conways-game-of-life
  • Loading branch information
Techiral authored Jul 12, 2024
2 parents ade2ca7 + c071136 commit da39e0c
Showing 1 changed file with 115 additions and 0 deletions.
115 changes: 115 additions & 0 deletions program-for-conways-game-of-life
Original file line number Diff line number Diff line change
@@ -0,0 +1,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

0 comments on commit da39e0c

Please sign in to comment.