Josh Simani - 1 year ago 74

C++ Question

I am trying to make a sudoku checker function to see if the entered board is valid. To do this, I would generate a board, and check each individual row, column, and set of 9 squares to see if they each contain the numbers 1-9. If they do not contain each number in that specific region, the function would

`return false;`

Right now, I'm focusing on checking the rows of the sudoku board. I didn't want to have to input all 9 rows when checking the compiled version, so I am focusing on just a single row right now.

The program checks to see if the row has all 9 numbers in it. If the row is missing one of the numbers (1-9), it will

`return false;`

However, the program always says that it is a valid board, even if it is missing some of the required numbers.

Here is a copy of my code so far:

`#include <iostream>`

using namespace std;

const int DIMEN = 9;

bool is_valid(int []);

int main()

{

int board[DIMEN];

cout << "Enter values for array.\n";

for (int arraynumber = 0; arraynumber < DIMEN; arraynumber++)

{

cout << "\nArray [" << arraynumber << "]? ";

cin >> board[arraynumber];

}

bool valid = is_valid(board);

if (valid)

{

cout << "\nValid Board!\n";

}

else

{

cout << "\nInvalid Board!\n";

}

return 0;

}

bool is_valid(int isvalid[])

{

bool check_row = false;

//Checks to see if the row has all required numbers

bool check_number = false;

//Checks to see if the row contains a specific number in it

while (!(check_row))

//While the row doesn't yet have all required numbers in it

{

for (int number = 1; number <= DIMEN; number++)

// Goes through each # (1-9) to see if the row contains that #

{

while (!(check_number))

//While the row doesn't yet have the number in it

{

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

//Move across the row from column 0 to 8

{

if (isvalid[i] == number)

/* If the value for this specific element of the array

equals the number */

{

check_number = true;

//The row has the number in it

}

}

if (!(check_number))

/* If the number was not found in the row by the

end of the for loop */

{ return false;

//End the program saying the board is invalid

}

}

}

check_row = true;

}

return true;

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You never set `check_number`

back to false when you start checking a new number.

Having said that, your code is pretty complex and hard to read. You could do:

```
bool is_valid(int row[])
{
for(int number = 1; number <= 9; number++)
{
bool found = false;
for(int i = 0; i < DIMEN; i++) {
found = (row[i] == number);
if (found) break;
}
// We've looked at each spot in the row and not found number
// so we know the row isn't valid.
if (!found) return false;
}
// If we get here we must have found every number so the row is valid
return true;
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**