Sudoku Check Complete Board Function  
Author Message
Montana47





PostPosted: Visual C# General, Sudoku Check Complete Board Function Top

Hi, i have a 2d array containing all the sudoku numbers, i have created a function to check whether a number is duplicated in any of the rows or columns, but now i need to check whether their are duplicates in the nine 3 x 3 boxes. anyone have any ideas

heres the code so far to check the rows and cols:

for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
{
for (int col2 = 0; col2 < 9; col2++)
{
if (col2 != col)
{
if (board.Cells[row, col].Value == board.Cells[row, col2].Value)
{
TextBox1.Text = "Duplicate";
}
}
}
for (int row2 = 0; row2 < 9; row2++)
{
if (row2 != row)
{
if (board.Cells[row, col].Value == board.Cells[row2, col].Value)
{
TextBox1.Text = "Duplicate";
}
}
}
}


Visual C#20  
 
 
Montana47





PostPosted: Visual C# General, Sudoku Check Complete Board Function Top

ok, i got this to check 1st 3 x 3. is it advisable to make 9 of these

int total = 0;
for (int row = 0; row <= 2; row++)
{
for (int col = 0; col <= 2; col++)
{
total = total + Convert.ToInt16(board.Cells[row, col].Value);

}
}
if (total != 45)
{
TextBox1.Text = "Duplicate";
}

for (int row = 3; row <= 5; row++)
{
for (int col = 3; col <= 5; col++)
{
total = total + Convert.ToInt16(board.Cells[row, col].Value);

}
}
if (total != 45)
{
TextBox1.Text = "Duplicate";
}

 
 
cverdon





PostPosted: Visual C# General, Sudoku Check Complete Board Function Top

Hi,

You can simplify a lot your algorithm if you have these 3 arrays:

bool rows[9][9];
bool columns[9][9];
bool squares[3][3][9];

    for (int y=0; y<9; y++) {

        for (int x=0; x<9; x++) {

            int val = table[x][y];

            if (val!=(int)-1) {
                //cell not empty
                 if (rows[y][val-1] ||

                     columns[x][val-1] ||

                     squares[x/3][y/3][val-1])

                 {

                      //duplicate

                 }

                rows[y][val-1] = true;

                columns[x][val-1] = true;

                squares[x/3][y/3][val-1] = true;

            }

        }

    }

table[x][ y ] is equivalent to your board.Cells[row, col].Value.

If you want the code of my soduku solver I wrote during a sociology class just ask :)

Charles