codefail
codefail

Reputation: 381

array loop not working correctly? c++

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;

Upvotes: 3

Views: 332

Answers (4)

fredoverflow
fredoverflow

Reputation: 263340

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

Upvotes: 0

Chris O
Chris O

Reputation: 5037

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

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 225162

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?

Upvotes: 1

Matt
Matt

Reputation: 2055

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

Upvotes: 12

Related Questions