-
The Game of Life problem
Hey, I have an assignment called the Game of Life. If you haven't heard of it, feel free to look it up. Anyway, the problem I am having is the algorithm I have to compute if the living cell has any neighbors is not producing anything. I know that the code is a little redundant but if you have any suggestions, please help.
This code basically goes through the array and adds up all the neighbors and if they are less than 2 or more than 3, then the current node is dead(i.e. 0)
Here is the code:
Code:
void liveon(int g1[][22],int g2[][22])
{
for(int r=0;r<22;r++)
for(int c=0;c<22;c++)
while(g1[r][c]=1)
{
if(g1[r-1][c-1]+g1[r-1][c]+g1[r-1][c+1]//top of block
+ g1[r][c-1]+g1[r][c+1] //middle of block
+ g1[r][c]+g1[r][c]+g1[r][c]<2 //bottom of block
||
g1[r-1][c-1]+g1[r-1][c]+g1[r-1][c+1] //top of block
+ g1[r][c-1]+g1[r][c+1] //middle of block
+ g1[r+1][c-1]+g1[r+1][c]+g1[r+1][c+1]>3) // bottom
g1[r][c]=0;
}
//copy to second array
}
-
Well how about a nice and simple
Code:
for(int r=0;r<22;r++) {
for(int c=0;c<22;c++) {
neighbours = count_neighbours( g1, r, c );
if ( neighbours == 2 || neighbours == 3 ) {
// we're alive!
g2[r][c] = 1;
} else {
// alas, poor Yorik
g2[r][c] = 0;
}
}
}
> g1[r-1][c-1]
At r=0, c=0, this is way off the ends of the array
You need to allow for this in your count_neighbours() function
> while(g1[r][c]=1)
You probably meant while(g1[r][c]==1)
But I'm not sure that fixes anything.
-
Also, I'm not sure what you are trying to accomplish with the while function. You should either kill the cell or keep it alive, but either way you don't need the while loop. With the algorithm that you have, if the cell is to be kept alive then it will just run into an infinite loop.
-
Yeah, I noticed, I changed it to an if statement and that seemed to work.. thanks for the help
-
-
so have I... http://www.johnshaoonline.com/frame.htm (it's called 'Life', Ironically ;)) I don't think I have my code there, but those are all open-source, so just post here or PM me if you need/want my code...
P.S. - In my code, there's a problem writing back to the array so it kinda wraps around one or two columns... I just haven't gotten around to finding the problem...