Question:
C Programming - Sudoku mini grid (3x3) validation?
?
2016-10-25 15:02:50 UTC
I've been researching and trying to think of how to validate a small 3x3 grid in a sudoku puzzle which checks for repeated numbers. I'm providing external links for my code since it is too large to fit.

This is one function to determine whether the sudoku puzzle is valid by rows, columns, and grid: http://codepad.org/QPN4spOy
Three answers:
?
2016-10-26 02:34:23 UTC
int check3x3(int array[3][3])

{

int checker[9],i,j;



for (i = 0;i < 9;checker[i++] = 0);



for (i = 0;i < 3;i++)

for (j = 0;j < 3;j++)

{

if ((array[i][j] < 1) || (array[i][j] > 9))

return(2);



if (checker[array[i][j] - 1])

return(1);



checker[array[i][j] - 1]++;

}



return (0);

}



main()

{

int a[3][3];



a[0][0] = 1;

a[0][1] = 2;

a[0][2] = 3;

a[1][0] = 4;

a[1][1] = 5;

a[1][2] = 7;

a[2][0] = 6;

a[2][1] = 8;

a[2][2] = 9;



printf("%d\n",check3x3(a));

}







Ignore the main section. This was just for testing.



Return 0 = no duplicates.

Return 1 = duplicates.

Return 2 = value out of range.



1 or 2 may be returned depending which error occurs first.
cja
2016-10-27 13:41:30 UTC
Your 'for' loops are nested 4 deep, you don't need that many. The check to see if all numbers are present, and there are no duplicates, isn't that hard. Here's an example (similar to Richard's concept, but I'm not a fan of multiple returns from a function):



bool checkSudokuSubMatrix(unsigned **a, size_t yOffset, size_t xOffset) {

. . unsigned check = 0;

. . size_t i, j;



. . for (i = 0; i < SUB_MATRIX_ROWS; i++) {

. . . . for (j = 0; j < SUB_MATRIX_COLS; j++) {

. . . . . . check |= (1 << (a[i + yOffset][j + xOffset] - 1));

. . . . }

. . }

. . return check == 0x1FF;

}
Tasm
2016-10-25 15:06:12 UTC
The easiest way is to put the results in an array and sum it up. It should equal 45.



The just sum up the 3 indexs for each row column, diagonal and the should all equal


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...