Homework question (C++)

TheBlackOut

Member
Apr 13, 2008
147
0
0
Hey guys. I am new to programming and am taking an introduction class in C++. We have a homework assignment which we are suppose to implement Conway's Game of Life. It's a simple assignment with simple rules but I can't seem to get it to run properly.

Most of the framework of the code was provided by the professor but we had to do the part where we apply the rules of the game. I am having a feeling it is the way I am trying to use memset and memcpy but it could be an error on my part I have an issue finding. I've had two friends look at it but they're not too experienced and can't seem to help.

To code is on pastebin here: http://pastebin.com/96ZKe4TH
(Unsure if it's usually better to just link it or put it within my post)

The rules assigned are the original ones that can be viewed on Wikipedia:
- Any live cell with fewer than two live neighbours dies, as if caused by under-population.
- Any live cell with two or three live neighbours lives on to the next generation.
- Any live cell with more than three live neighbours dies, as if by overcrowding.
- Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

Any hints as to what the issue is and any improvements that could be done would be very welcomed! The input and output will be on the command line and any input is like such: #ofRow [whitespace] #ofColumn

I keep trying to test this and it doesn't work at all:
1 1
1 2
2 1

That should result in 2 2 becoming alive, but it doesn't at all and then a weird pattern repeats after a few generations.
 

mv2devnull

Golden Member
Apr 13, 2010
1,526
160
106
You do initialize the livetest counter to 0 only in the beginning of each row, rather than for each cell as you should.
Code:
  for (i = 1; i <= NumRows; i++)
  {
    for (j = 1, livetest = 0; j <= NumCols; j++)
    {
PS. iostream is a C++ feature, but the rest of the code could be plain C. The Standard Template Library of C++ offers Container classes, such as std::vector, and algorithms. Together, those make operations like copy of an array, or assignment of "false" to every cell of an array, very simple and less error-prone than the memset/memcpy from the C-library.
 

sao123

Lifer
May 27, 2002
12,653
205
106
It seems to me your program could be a lot simpler if you defined reusable functions with a few easy loops...

Code:
void setboardtofalse(board, max_rows, max_columns)
{
for(int X=0; X< max_rows; X++)
for(int Y=0; Y< Max_columns; Y++)
board[X][Y] = false;
}
 
int count_neighbors(board,X_row,Y_col)
{
int count = 0;
for(int A=X_row-1; A<=X_row+1;A++)
for(int B=Y_col-1; B<=Y_col+1; B++)
{ if (board[X_rox][Y_col] ); 
if !(A == X_row && B== Y_col) count++; }
return count; 
}