Expected output of this problem : Initial world * * *** *** ====================
ID: 3878809 • Letter: E
Question
Expected output of this problem :
Initial world
*
*
***
***
===========================
Generation: 1
* *
**
*
*
*
*
====================
Generation: 2
*
* *
**
***
====================
Generation: 3
*
**
**
*
*
*
====================
Generation: 4
*
*
***
***
====================
Generation: 5
* *
**
* *
*
*
====================
Generation: 6
*
* *
**
***
====================
Generation: 7
*
**
** *
*
*
====================
Generation: 8
*
*
***
***
====================
Generation: 9
* *
** *
* *
*
====================
Generation: 10
*
* *
** ***
====================
Explanation / Answer
You can define the maximum number of lines in the Conway's Game of life in MXSZ. By default, I have set it to 10^5 + 1.
Since the question did not ask for comments, I have not written the comments.
The Code is as follows:
#include <bits/stdc++.h>
using namespace std;
#define MXSZ 100001
/*
Conway's Game Of Life
*/
string str[MXSZ],newstr[MXSZ];
int len,counter=0;
int will_live(int x,int y,int required)
{
int arr[]={1,1,0,-1,-1,-1,0,1};
int brr[]={0,1,1,1,0,-1,-1,-1};
int cnt=0;
for(int i=0;i<8;i++)
{
if(str[x+arr[i]][y+brr[i]]=='*')
cnt++;
}
if(cnt==required)
return 1;
else
return 0;
}
void PrintGen()
{
for(int i=1;i<counter+1;i++)
{
for(int j=1;j<len;j++)
{
if(str[i][j]=='-' && will_live(i,j,3))
{
newstr[i][j]='*';
}
else if(str[i][j]=='*' && ( !will_live(i,j,2) && !will_live(i,j,3) ) )
{
newstr[i][j]='-';
}
else
newstr[i][j]=str[i][j];
if(newstr[i][j]=='-')
cout<<" ";
else
cout<<"*";
}
cout<<endl;
}
for(int i=1;i<=counter;i++)
str[i]=newstr[i];
}
void PrintInitialLine(string s)
{
for(int i=1;i<s.length()-1;i++)
{
if(s[i]=='-')
cout<<" ";
else
cout<<"*";
}
cout<<endl;
}
int main()
{
fstream myfile;
myfile.open("life.txt",ios::in);
string line;
cout<<"Initial world"<<endl;
while(getline(myfile,line))
{
counter++;
line='-'+line+'-';
str[counter]=line;
newstr[counter]=line;
PrintInitialLine(line);
len=str[counter].length()-1;
}
for(int i=1;i<=10;i++)
{
cout<<"================="<<endl;
cout<<"Generation "<<i<<endl;
PrintGen();
}
myfile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.