aboutsummaryrefslogtreecommitdiffstats
path: root/c/sudoku.c
diff options
context:
space:
mode:
authorBryan Brattlof <hello@bryanbrattlof.com>2020-08-07 22:13:42 -0400
committerBryan Brattlof <hello@bryanbrattlof.com>2020-08-07 22:13:42 -0400
commit63c0daafdc534d9932c50df3348032b6f55af372 (patch)
treeee709ef7d399be09d5e4d12dc446265ec4d68a5b /c/sudoku.c
parent98c9c7f41ab7bda5a727eba15638756c1d964630 (diff)
downloadsudoku-63c0daafdc534d9932c50df3348032b6f55af372.tar.gz
sudoku-63c0daafdc534d9932c50df3348032b6f55af372.tar.bz2
c: add functions to search for possabilities
the inBox, inCol, inRow functions search the 3x3 box, column, and row of the index square given (i), for the possible number (n) given. If the number is found in the box, column, or row, the number (n) is skipped and another is tried until a possibility is found. If all possibilities are exausted the 'solve()' function will backtrack. The backtracking isn't emplemented yet.
Diffstat (limited to 'c/sudoku.c')
-rw-r--r--c/sudoku.c50
1 files changed, 48 insertions, 2 deletions
diff --git a/c/sudoku.c b/c/sudoku.c
index 040ba8d..072d957 100644
--- a/c/sudoku.c
+++ b/c/sudoku.c
@@ -1,6 +1,44 @@
+#include <stdbool.h>
#include <stdio.h>
+bool inBox(int i, int n, char puzzle[])
+{
+ int boxRow = (i / 9 / 3) * 27;
+ int boxCol = ((i % 9) / 3) * 3;
+
+ for(int j = boxRow; j < boxRow + 27; j += 9) {
+ for(int k = boxCol; k < boxCol + 3; k++){
+ if(puzzle[j + k] - '0' == n)
+ return true;
+ }
+ }
+ return false;
+}
+
+
+bool inCol(int i, int n, char puzzle[])
+{
+ int col = i % 9;
+ for(int j = col; j < 81; j += 9) {
+ if(puzzle[j] - '0' == n)
+ return true;
+ }
+ return false;
+}
+
+
+bool inRow(int i, int n, char puzzle[])
+{
+ int row = i/9;
+ for(int j = row; j/9 <= row; j++) {
+ if(puzzle[j] - '0' == n)
+ return true;
+ }
+ return false;
+}
+
+
char* solve(char puzzle[])
{
@@ -11,8 +49,15 @@ char* solve(char puzzle[])
goto next; // this square is answered
}
- // found an unanswered square
- //printf("%d", puzzle[i] - '0');
+ for(int n=1; n<10; n++) {
+ if(inRow(i, n, puzzle) || inCol(i, n, puzzle) || inBox(i, n, puzzle))
+ continue;
+
+ puzzle[i] = n + '0';
+ return solve(puzzle);
+ }
+
+ // need to backtrack
next:
i++;
@@ -41,6 +86,7 @@ void display(char puzzle[])
int main(int argc, char *argv[])
{
+ display(argv[1]);
for(int i=1; i < argc; i++) {
char* puzzle = solve(argv[i]);