#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int Size = 20;
void displayGrid(const bool [][Size]);
void nextGen(bool [][Size], bool [][Size]);
int getNeighborCount(const bool [][Size], int, int);
int main()
{
ifstream datafile;
string filename;
cout << "The input values from the file will begin the first generation." << endl << endl;
cout << "Follow the prompts to create new generations or terminate the program." << endl << endl;
// Initilize the grid to all dead cells
bool Grid[Size][Size];
for (int i=0; i < Size; i++)
for (int j=0; j < Size; j++)
Grid[i][j] = false;
int row, col;
// Prompt user for filename.
cout << "Please enter the file name containing input values. " << endl;
cout << endl;
cin >> filename;
cout << fixed << showpoint;
datafile.open(filename.c_str());
if (!datafile)
{
cout << "File not found" << endl;
return 1;
}
while (datafile)
{
datafile >> row >> col;
if ( row>=0 && row<Size && col>=0 && col<Size) // checks for compatability
Grid[row][col] = true;
}
while ( row != -1);
displayGrid(Grid);
char answer;
bool temp[Size][Size];
cout << "Display next generation? Y/N ";
cin >> answer;
while (answer == 'y' || answer == 'Y')
{
nextGen(Grid, temp);
displayGrid(Grid);
cout << "Display next generation? Y/N ";
cin >> answer;
}
return 0;
}
void displayGrid(const bool World[][Size])
{
cout << endl;
for (int i=0; i < Size; i++)
{
for (int j=0; j < Size; j++)
if (World[i][j] == true)
cout << "X ";
else cout << ". ";
cout << endl;
}
}
// Makes a temporary generation based on the current grid. Calls the
// getNeighborCount function and makes a live/die decision. Then the
// temporary world gets copied over to a new generation.
void nextGen(bool World[][Size], bool tempWorld[][Size])
{
int neighborcount;
for (int i=0; i < Size; i++)
for (int j=0; j < Size; j++)
{
neighborcount = getNeighborCount(World,i,j);
if (neighborcount == 2) // 2 neighbors stays alive
tempWorld[i][j] = World[i][j];
else if (neighborcount == 3)
tempWorld[i][j] = true; // 3 neighbors stays alive
else tempWorld[i][j] = false; // 1 and 4+ neighbors = dead
}
// copy tempWorld to World
{
for (int i=0; i < Size; i++)
for (int j=0; j < Size; j++)
World[i][j] = tempWorld[i][j];
}
}
int getNeighborCount(const bool World[][Size], int row, int col)
// Counts neighbors in a row/column pair
{
int count=0;
if (row > 0)
{
if (col > 0 && World[row-1][col-1] == true)
count++;
if (col < Size-1 && World[row-1][col+1] == true)
count++;
if (World[row-1][col] == true)
count++;
}
if (row < Size - 1)
{
if (col > 0 && World[row+1][col-1] == true)
count++;
if (col < Size - 1 && World[row+1][col+1] == true)
count++;
if (World[row+1][col] == true)
count++;
}
if (col > 0 && World[row][col-1] == true)
count++;
if (col < Size - 1 && World[row][col+1] == true)
count++;
return count;
}