aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBryan Brattlof <hello@bryanbrattlof.com>2020-08-08 19:14:32 -0400
committerBryan Brattlof <hello@bryanbrattlof.com>2020-08-08 19:15:10 -0400
commitbbbe3fc8d2b94689979529e5ce4d38075e296f7e (patch)
treece3e579f3fd3481b15a5880bd64ecdffa023242b
parent63c0daafdc534d9932c50df3348032b6f55af372 (diff)
downloadsudoku-bbbe3fc8d2b94689979529e5ce4d38075e296f7e.tar.gz
sudoku-bbbe3fc8d2b94689979529e5ce4d38075e296f7e.tar.bz2
c: switch to a global PUZZLE
In order to stop passing a puzzle pointer around to the different functions. I decided to create a global PUZZLE object every function can access.
-rw-r--r--c/sudoku.c47
1 files changed, 26 insertions, 21 deletions
diff --git a/c/sudoku.c b/c/sudoku.c
index 072d957..f2af05f 100644
--- a/c/sudoku.c
+++ b/c/sudoku.c
@@ -1,15 +1,18 @@
#include <stdbool.h>
+#include <string.h>
#include <stdio.h>
-bool inBox(int i, int n, char puzzle[])
+char PUZZLE[81];
+
+
+bool inBox(int i, int n)
{
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)
+ if(PUZZLE[j + k] - '0' == n)
return true;
}
}
@@ -17,63 +20,64 @@ bool inBox(int i, int n, char puzzle[])
}
-bool inCol(int i, int n, char puzzle[])
+bool inCol(int i, int n)
{
int col = i % 9;
for(int j = col; j < 81; j += 9) {
- if(puzzle[j] - '0' == n)
+ if(PUZZLE[j] - '0' == n)
return true;
}
return false;
}
-bool inRow(int i, int n, char puzzle[])
+bool inRow(int i, int n)
{
int row = i/9;
for(int j = row; j/9 <= row; j++) {
- if(puzzle[j] - '0' == n)
+ if(PUZZLE[j] - '0' == n)
return true;
}
return false;
}
-char* solve(char puzzle[])
+bool solve()
{
/* search for an unanswered square */
int i = 0;
- while(puzzle[i] != '\0') {
- if(puzzle[i] - '0' != 0) {
+ while(PUZZLE[i] != '\0') {
+ if(PUZZLE[i] - '0' != 0) {
goto next; // this square is answered
}
for(int n=1; n<10; n++) {
- if(inRow(i, n, puzzle) || inCol(i, n, puzzle) || inBox(i, n, puzzle))
+ if(inRow(i, n) || inCol(i, n) || inBox(i, n))
continue;
- puzzle[i] = n + '0';
- return solve(puzzle);
+ PUZZLE[i] = n + '0';
+ if(solve(PUZZLE))
+ return true;
}
// need to backtrack
+ PUZZLE[i] = 0 + '0';
+ return false;
next:
i++;
}
-
- return puzzle; // we solved it!
}
-void display(char puzzle[])
+void display()
{
printf("\n ");
int i = 0;
- while(puzzle[i] != '\0') {
- printf(" %d", puzzle[i] - '0');
+ while(PUZZLE[i] != '\0') {
+ printf(" %d", PUZZLE[i] - '0');
if(i % 9 == 8)
printf("\n ");
@@ -86,11 +90,12 @@ 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]);
+ strcpy(PUZZLE, argv[i]);
+ display();
- display(puzzle);
+ solve();
+ display();
}
return 0;
}