Question:

C++ Help? Conways game of life?

by  |  earlier

0 LIKES UnLike

Can someone please help me with my program? If anyone is familair with conways game of life i would really appreciate it. Im making my function to count neighbours, but it doesnt seem to be working correctly.

The function is supposed to count the number of neighbours which are alive, but I dont think it is working correctly.

When I output the result of neighbours it outputs something like 250, when infact there are only 20 alive cells in the array

Any help? Thanks =)

int countAlive(char grid[SIZE][SIZE])

{

int neighbour = 0;

for(int row = 1; row < SIZE-1; row++)

for(int col = 1; col < SIZE-1; col++)

{if(grid[row-1][col-1] == '*') neighbour++;

if(grid[row-1][col] == '*') neighbour++;

if(grid[row-1][col+1] == '*') neighbour++;

if(grid[row][col-1] == '*') neighbour++;

if(grid[row][col+1] == '*') neighbour++;

if(grid[row+1][col-1] == '*') neighbour++;

if(grid[row+1][col] == '*') neighbour++;

if(grid[row+1][col+1] == '*') neighbour++;}

return neighbour;

}

 Tags:

   Report

1 ANSWERS


  1. Well...each cell is neighbor to 8 others.  So if there are 20 alive cells, then it would make sense for the value of &quot;neighbour&quot; to be around 160.

    As far as critiquing your actual code, though...it sounds like you are confusing &quot;counting total number of alive cells&quot; with &quot;counting a cell&#039;s alive neighbors&quot;.

    If you just want to count the number of cells that are alive, get rid of all the if&#039;s and just put if (grid[row][col] == &#039;*&#039;).  And of course you&#039;ll have to change the limits of your for loops to include the left and right columns, and the top and bottom rows.

    The ifs you have are good for counting a particular cell&#039;s living neighbors.  But there&#039;s not really any point in adding up the total of that.

    To simplify...say this is your grid:

    ----

    -**-

    ----

    You want to know that there are 2 living cells.  You want to know that in my poor example, every cell has either 1 or 2 living neighbors.  But even though the total of all the cells&#039; neighbor counts is 16 (going left-to-right and then top-to-bottom, 1+2+2+1 + 1+1+1+1 + 1+2+2+1), that number is probably not useful to you.

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions