So my task was to write a boolena method to count the number of live neighbour of a cell
t is a 2D boolean array with a row and column position, i have to count the number of surrounding cells that contain the value true.

So the index number given to me were
i-1, j-1 | i-1, j | i-1, j+1
i, j-1 | i, j | i, j+1
i+1, j-1 | i+1, j | i+1, j+1t

where i represents row and j represent column

 public static boolean[][] nextGeneration(boolean[][] board1)
        {
            int count = 0;

            if (row-1 >= 0 && board[col-1][row] == true) {

                count++;

            }

            if (row-1 >= 0 && board[col][row] == true){

                count++;

            }

            if (row-1 >=0 && board[col+1][row] == true){

                count++;

            }

            if (row >=0 && board[col-1][row] == true){

                count++;

            }

            if (row < col && board[col][row] == true) {

                count++;

            }

            if (row < 0 && board[col+1][row] == true) {

                count++;

            }

            if (row+1 < col && board[col-1][row] == true) {

                count++;

            }

            if (row+1 < col && board[col][row] == true) {

                count++;

            }

            if (row+1 < col && board[col+1][row] == true){

                count++;}

            return count;

        }

All opinions valued! thanks

That's not C++, but the algorithm isn't exactly language specific. To simplify things I'd suggest a nested loop:

// Check the previous, current, and next row
for (int i = row - 1; i <= row + 1; ++i) {
    // Exclude invalid row indices
    if (i < 0 || i >= board_rows)
        continue;

    // Check the previous, current, and next column
    for (int j = col - 1; j <= col + 1; ++j) {
        // Exclude invalid column indices
        if (j < 0 || j >= board_cols)
            continue;

        // Increment if the cell is true, excluding self
        if (!(i == row && j == col) && board[i][j])
            ++count;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.