Solved! Get answer or ask a different Question 21448

Can some please explain this Function in an algorithmic term. The sequence of how it works.

void Grid::nextRule()

 {

    int numSurrounding = 0;

    bool tempGrid [height][width];

    for (int i = 0; i < height ; i++)

    {

            for (int j = 0; j < width ; j++)

            {

                    if ( (i+1) < height && grid[i + 1][j] == true )

                    {

                            numSurrounding++;

                    }

                    if ( (i-1) >= 0 && grid[i – 1][j] == true )

                    {

                            numSurrounding++;

                    }

                    if ( (j+1) < width && grid[i][j+1] == true )

                    {

                            numSurrounding++;

                    }

                    if ( (j-1) >= 0 && grid[i][j-1] == true )

                    {

                            numSurrounding++;

                    }

                    if ( (i+1) < height && (j+1) < width && grid[i+1][j+1] == true )

                    {

                            numSurrounding++;

                    }

                    if ( (i+1) < height && (j-1) >= 0 && grid[i+1][j-1] == true )

                    {

                            numSurrounding++;

                    }

                    if ( (i-1) >= 0 && (j+1) < width && grid[i-1][j+1] == true )

                    {

                            numSurrounding++;

                    }

                    if ( (i-1) >= 0 && (j-1) >= 0 && grid[i-1][j-1] == true )

                    {

                            numSurrounding++;

                    }

               //Applying the rules of the game base on the result of the surrounding  neighbor cell

               // if neighbor cell is < 2 the base cell dies from isolation, if the neighbor > 3 the base cell dies from overpopulation

                    if (numSurrounding < 2 || numSurrounding > 3)

                    {

                            tempGrid[i][j] = false;

                    }

                    else if (numSurrounding == 2) // if the neighbor cell is equal to 2 then birth is given to the dead cell

                    {

                            tempGrid[i][j] = grid[i][j];

                    }

                    else if (numSurrounding == 3) // if the neighbor cell is equal to 3 then the base cell survive for the next generation

                    {

                            tempGrid[i][j] = true;

                    }

                    numSurrounding = 0;

            }

    }

    for (int i = 0 ; i < height ; i++ )

    {

            for (int j = 0 ; j < width ; j++ )

            {

                    grid[i][j] = tempGrid[i][j];

            }

    }

}

 
"Not answered?"
Get the Answer