Reputation: 13
I am making a code of Conways game of life. I am using a function to check all the cells surrounding each alive cell and store how many times they each show up. I am storing the results in a 2 dimensional array called surroundlist.
void updateAlive(){
int surroundlist[sizeX][sizeY],i,j;
for (j=0; j<sizeY; ++j){
for (i=0; i<sizeX; ++i){
surroundlist[i][j]=0;
}
}
for (i=0; i<alivecells; ++i){
++surroundlist[(alive[i].Xcoord-1)][(alive[i].Ycoord-1)];
++surroundlist[(alive[i].Xcoord)][(alive[i].Ycoord-1)];
++surroundlist[(alive[i].Xcoord+1)][(alive[i].Ycoord-1)];
++surroundlist[(alive[i].Xcoord-1)][(alive[i].Ycoord)];
++surroundlist[(alive[i].Xcoord+1)][(alive[i].Ycoord)];
++surroundlist[(alive[i].Xcoord-1)][(alive[i].Ycoord+1)];
++surroundlist[(alive[i].Xcoord)][(alive[i].Ycoord+1)];
++surroundlist[(alive[i].Xcoord+1)][(alive[i].Ycoord+1)];
}
}
alive is a structure containing the x and y coordinates of each alive cell, shown here:
typedef struct {//structure contains all alive cells
int Xcoord;//x coord of alive cell
int Ycoord;//y coord of alive cell
} point;
point alive[sizeX * sizeY - 1];
this function works fine, unless the coordinate of an alive cell is on an edge e.g. (0,0). In which case the program will usually error with a segmentation fault, as its trying to place a value in a cell that does not exist.
is there a function that can be used to check if a cell exists in an array that I can use before updating each surrounding cell to check if it exists?
Upvotes: 0
Views: 171
Reputation: 32586
this function works fine
no, on the borders you count non adjacent cells placed on the opposite next/previous line
... unless the coordinate of an alive cell is on an edge e.g. (0,0)
you write out of surroundlist when alive is for a point on the first and last line
is there a function that can be used to check if a cell exists in an array that I can use before updating each surrounding cell to check if it exists?
you need to check you can consider the cell each time you add/remove 1 on the coordinate, or you have to do a special case for the borders. An other way is to place the rectangle centered in a rectangle having two more lines and columns, and never put an alive element in these extra lines/columns
Upvotes: 2