views:

108

answers:

4

Trying to count how many elements within the array are not equal to 0, is something set up wrong?

I'd like to check all values in the array (it's a sudoku board) and then when all elements are "full" I need to return true. Is something off?

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;
+12  A: 

You have = rather than ==

if (totalCount == 81)

is the correct line.

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

if (81)

And since in C++ anything nonzero is true, this is always true

Matt
+1 Well spotted.
Mark Byers
I've been staring at this for too long. Thanks, now I feel stupid.
codefail
get into the habit of compiling with high levels of warnings turned on - the compiler would have spotted this for you
pm100
+1 @pm100, or learn to use a debugger.
Carl Norum
Or write it like this: if( 81 == totalCount ) then it doesnt matter what warning level you are on.
John Dibling
@John: Ew... :)
GMan
@Gman: All the college kids are doing it these days!
John Dibling
@John: I'm not! :)
GMan
@John: Until you have `if (var_a = var_b)` where only warnings can save you.
KennyTM
+1  A: 

You have a = that should be a ==. That's all I'll say, since it's homework.

Also, why do you have a constant for BOARD_SIZE, then check against 81 at the end? Wouldn't checking against BOARD_SIZE * BOARD_SIZE be better?

Carl Norum
I guess that works as well, but in this case BOARD_SIZE does not change (declared as const elsewhere) so it's okay (albeit bad programming?)
codefail
@igor, sure, but if it doesn't change why don't you have 9 everywhere, that's less typing than `BOARD_SIZE` if you don't care about it being a constant.
Carl Norum
A: 

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

Chris O
A: 

You can leave the function as soon as you find the first 0, and it's possible to solve this 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 algorithms to hand-written loops:

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];
}
FredOverflow