Error in checking for win conditions in a function using arrays.

I am trying to write a program for the game sudoku. I have the following function to check each row, column must contain each value in {1..9} exactly once. But I have trouble in doing so. I cannot find my error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// array row[] is of length at least 9
bool sudoku_row_ok(int row[]) {
int sum=0;
int i;

  for(i=0; i<9; i++) {
    if(row[i] < 1 || row[i] > 9)
        return false;            // out of range
    sum += row[i];
  }
  if(sum == 45)     // checking for 1+2+3+4+5+6+7+8+9 = 45
    return true;
  else
    return false;
}


The check is incorrect. The row [1, 1, 4, 4, 5, 6, 7, 8, 9] adds up to 45 but is not a winning state.
@helios Then in what way can I write the check statement
Use an array to store the occurrences of each value and then check that they all appear exactly once.
Using the STL makes it easy:
1
2
3
4
5
6
7
8
9
10
11
12
// array row[] is of length at least 9
bool sudoku_row_ok(int row[]) 
{
  vector<int> v(row, row + 9);

  for (int num = 1; num <= 9; num++) // test each value between 1 and 9
  {
    if (std::find(v.begin(), v.end(), num) == v.end()) // not found
      return false;
  }
  return true;
}
1
2
3
4
5
6
7
8
9
10
#include <algorithm>

// return true if array row[] (length at least 9) contains each value in [1,9]
bool sudoku_row_ok( const int row[] )
{
    static const int unique_1_to_9[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;

    // https://en.cppreference.com/w/cpp/algorithm/is_permutation
    return std::is_permutation( row, row+9, unique_1_to_9 ) ;
}
Topic archived. No new replies allowed.