checking available values for sudoku

I'm making a program to play sudoku. I just wanted to know if there was a more efficient way to check if the value the user inputs in a square is a valid value. Right now I have three separate for loops checking the row, column and the square the value is in.

The for loop that checks the square isn't exactly how I want it. Currently it only checks the values in the first square, I'm still working on that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
cout << "What are the coordinates of the square: ";
cin >> coord1 >> coord2;

cout << "What is the value at \'" << (char)toupper(coord1)
     << coord2 << "\': ";
cin >> value;

char row = (char)toupper(coord1) - 'A';
int col = coord2 - 1;

//checks the numbers in the column to see if any match the user value
for (count = 0; count < 9; count++)
{
   if (data[row][count] == value)
   {
      cout << "ERROR: Value \'" << value << "\' in square \'"
           << (char)toupper(coord1) << coord2 << "\' is invalid\n";
   }
}

//checks the numbers in the row to see if any match the user value
for (count = 0; count < 9; count++)
{
   if (data[count][col] == value)
   {
      cout << "ERROR: Value \'" << value << "\' in square \'"
           << (char)toupper(coord1) << coord2 << "\' is invalid\n";
   }
}

//checks the numbers in the square to see if any match the user value
for (int row = 0; count < 3; count++)
{
   for (int col = 0; col < 3; col++)
   {
      if (data[row][col] == value)
      {
         cout << "ERROR: Value \'" << value << "\' in square \'"
              << toupper(coord1) << coord2 << "\' is invalid\n";
      }
   }
}
Last edited on
Any way you do it, you'll still need to check rows, columns and a square. There is nothing inefficient about that. If you feel that you must, I suppose you could write smarter code only to check each number once (since some numbers in row, column and square will inevitably overlap). The gain would be somewhere between negligible (there are only 6 integer comparisons to save) and non existent (the extra logic you would need might take as much time as those 6 comparisons).

As for your square checking, if you divide coords by 3, you'll find which square you're on. Then add the appropriate offset to row and col on line 36.
Topic archived. No new replies allowed.