Array loop malfunctioning? C ++

Trying to count how many elements in the array are not 0, is something incorrectly set?

I want to check all the values ​​in an array (this is a sudoku board), and then when all the elements are "filled", I need to return true. Something is wrong?

bool boardFull(const Square board[BOARD_SIZE][BOARD_SIZE])
{
    int totalCount=0;
    for (int index1 = 0; index1 < BOARD_SIZE; index1++)
        for (int index2 = 0; index2 < BOARD_SIZE; index2++){ 
             if(board[index1][index2].number!=0)
                totalCount++;
        }
    if(totalCount=81)
        return true;
    else 
        return false;
+3
source share
4 answers

You have =, not ==

if (totalCount == 81)

is the correct line.

Doing this with a single "=" actually sets the value to 81 totalCount, so your test is needed:

if (81)

And since in C ++ all non-zero value is true, this is always true

+12
source

=, ==. , , .

, BOARD_SIZE, 81 ? BOARD_SIZE * BOARD_SIZE?

+1

Is If (totalCount = 81) a typo in this post or your code? Looks like you assigned a value there.

0
source

You can leave this function as soon as you find the first 0, and this can be solved with a single loop:

bool boardFull(const Square board[BOARD_SIZE][BOARD_SIZE])
{
    const Square* p = board[0];
    for (int n = BOARD_SIZE * BOARD_SIZE; n; --n, ++p)
    {
        if (p->number == 0) return false;
    }
    return true;
}

But I prefer handwriting loop algorithms:

struct Square
{
    int number;

    bool is_zero() const
    {
        return number == 0;
    }
};

#include <algorithm>
#include <functional>

bool boardFull(const Square board[BOARD_SIZE][BOARD_SIZE])
{
    return std::find_if(
        board[0],
        board[BOARD_SIZE],
        std::mem_fun_ref(&Square::is_zero)
    )== board[BOARD_SIZE];
}
0
source

Source: https://habr.com/ru/post/1739530/


All Articles