In 1970, mathematician John Conway developed the Game of Life (no, not the board
ID: 3704198 • Letter: I
Question
In 1970, mathematician John Conway developed the Game of Life (no, not the board game). Imagine a grid of cells, each cell in one of two states: alive or dead. Each cell interacts with its eight neighbors so that, over time, life in the cells will either begin or end, following a simple set of rules:
Any live cell with fewer than two live neighbors will die (from loneliness, perhaps)
Any live cell with two or three live neighbors remains alive
Any live cell with more than three live neighbors will die (from overcrowding, perhaps)
Any dead cell with exactly three live neighbors will become alive
When the main program begins, the user will input the number of time steps to be shown, the size of the grid (always square), and then the initial grid values. The size of the grid will be determined by the original input and will not change while the program is running. For simplicity, we will assume that any neighboring cells beyond the edges of the grid are dead. In the initial values and in the output, use "-" to indicate dead cells and "O" to indicate live cells (although you may of course represent these internally however you like (a boolean array, for example)). Running the program will look like the examples below.
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
int x[8]={0,1,1,1,0,-1,-1,-1};
int y[8]={1,1,0,-1,-1,-1,0,1};
bool isValid(int x,int y,int n)
{
return (x>=0 && y>=0 && x<n && y<n);
}
vector<string> playStep(vector<string> &grid)
{
int n=grid.size();
vector<string> ans(n);
for(int i=0;i<n;i++)
ans[i]=grid[i];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
int alive=0;
for(int k=0;k<8;k++)
if(isValid(i+x[k],j+y[k],n) && grid[i+x[k]][j+y[k]]=='O')
alive++;
if(grid[i][j]=='O')
{
if(alive<2)
ans[i][j]='-';
else
if(alive==2 || alive==3)
ans[i][j]='O';
else
if(alive>3)
ans[i][j]='-';
}
else
if(alive==3)
ans[i][j]='O';
}
return ans;
}
int main() {
// your code goes here
bool play=true;
do{
cout<<"The Game Of Life. ";
int timesteps,n,t;
cout<<"How many steps in time? ";
cin>>timesteps;
cout<<" What size is the grid? ";
cin>>n;
cout<<" Enter the initial grid layout: ";
vector<string> grid(n);
for(int i=0;i<n;i++)
cin>>grid[i];
t=timesteps;
while(timesteps)
{
grid=playStep(grid);
if(timesteps==1)
{
cout<<"After "<<t<<" step(s):"<<endl;
for(int i=0;i<n;i++)
cout<<grid[i]<<endl;
}
timesteps--;
}
cout<<" Do you want to play more?(Y/N) ";
char in;
cin>>in;
if(in=='Y')
play=true;
else
play=false;
}while(play);
return 0;
}