Leptonica  1.77.0
Image processing and image analysis suite
sudoku.c
Go to the documentation of this file.
1 /*====================================================================*
2  - Copyright (C) 2001 Leptonica. All rights reserved.
3  -
4  - Redistribution and use in source and binary forms, with or without
5  - modification, are permitted provided that the following conditions
6  - are met:
7  - 1. Redistributions of source code must retain the above copyright
8  - notice, this list of conditions and the following disclaimer.
9  - 2. Redistributions in binary form must reproduce the above
10  - copyright notice, this list of conditions and the following
11  - disclaimer in the documentation and/or other materials
12  - provided with the distribution.
13  -
14  - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15  - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16  - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17  - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY
18  - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  - OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
23  - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24  - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *====================================================================*/
26 
27 
141 #include "allheaders.h"
142 
143 
144 static l_int32 sudokuValidState(l_int32 *state);
145 static l_int32 sudokuNewGuess(L_SUDOKU *sud);
146 static l_int32 sudokuTestState(l_int32 *state, l_int32 index);
147 static l_int32 sudokuCompareState(L_SUDOKU *sud1, L_SUDOKU *sud2,
148  l_int32 quads, l_int32 *psame);
149 static l_int32 *sudokuRotateArray(l_int32 *array, l_int32 quads);
150 
151  /* An example of a valid solution */
152 static const char valid_solution[] = "3 8 7 2 6 4 1 9 5 "
153  "2 6 5 8 9 1 4 3 7 "
154  "1 4 9 5 3 7 6 8 2 "
155  "5 2 3 7 1 6 8 4 9 "
156  "7 1 6 9 4 8 2 5 3 "
157  "8 9 4 3 5 2 7 1 6 "
158  "9 7 2 1 8 5 3 6 4 "
159  "4 3 1 6 7 9 5 2 8 "
160  "6 5 8 4 2 3 9 7 1 ";
161 
162 
163 /*---------------------------------------------------------------------*
164  * Read input data from file or string *
165  *---------------------------------------------------------------------*/
180 l_int32 *
181 sudokuReadFile(const char *filename)
182 {
183 char *str, *strj;
184 l_uint8 *data;
185 l_int32 i, j, nlines, val, index, error;
186 l_int32 *array;
187 size_t size;
188 SARRAY *saline, *sa1, *sa2;
189 
190  PROCNAME("sudokuReadFile");
191 
192  if (!filename)
193  return (l_int32 *)ERROR_PTR("filename not defined", procName, NULL);
194  data = l_binaryRead(filename, &size);
195  sa1 = sarrayCreateLinesFromString((char *)data, 0);
196  sa2 = sarrayCreate(9);
197 
198  /* Filter out the comment lines; verify that there are 9 data lines */
199  nlines = sarrayGetCount(sa1);
200  for (i = 0; i < nlines; i++) {
201  str = sarrayGetString(sa1, i, L_NOCOPY);
202  if (str[0] != '#')
203  sarrayAddString(sa2, str, L_COPY);
204  }
205  LEPT_FREE(data);
206  sarrayDestroy(&sa1);
207  nlines = sarrayGetCount(sa2);
208  if (nlines != 9) {
209  sarrayDestroy(&sa2);
210  L_ERROR("file has %d lines\n", procName, nlines);
211  return (l_int32 *)ERROR_PTR("invalid file", procName, NULL);
212  }
213 
214  /* Read the data into the array, verifying that each data
215  * line has 9 numbers. */
216  error = FALSE;
217  array = (l_int32 *)LEPT_CALLOC(81, sizeof(l_int32));
218  for (i = 0, index = 0; i < 9; i++) {
219  str = sarrayGetString(sa2, i, L_NOCOPY);
220  saline = sarrayCreateWordsFromString(str);
221  if (sarrayGetCount(saline) != 9) {
222  error = TRUE;
223  sarrayDestroy(&saline);
224  break;
225  }
226  for (j = 0; j < 9; j++) {
227  strj = sarrayGetString(saline, j, L_NOCOPY);
228  if (sscanf(strj, "%d", &val) != 1)
229  error = TRUE;
230  else
231  array[index++] = val;
232  }
233  sarrayDestroy(&saline);
234  if (error) break;
235  }
236  sarrayDestroy(&sa2);
237 
238  if (error) {
239  LEPT_FREE(array);
240  return (l_int32 *)ERROR_PTR("invalid data", procName, NULL);
241  }
242 
243  return array;
244 }
245 
246 
259 l_int32 *
260 sudokuReadString(const char *str)
261 {
262 l_int32 i;
263 l_int32 *array;
264 
265  PROCNAME("sudokuReadString");
266 
267  if (!str)
268  return (l_int32 *)ERROR_PTR("str not defined", procName, NULL);
269 
270  /* Read in the initial solution */
271  array = (l_int32 *)LEPT_CALLOC(81, sizeof(l_int32));
272  for (i = 0; i < 81; i++) {
273  if (sscanf(str + 2 * i, "%d ", &array[i]) != 1) {
274  LEPT_FREE(array);
275  return (l_int32 *)ERROR_PTR("invalid format", procName, NULL);
276  }
277  }
278 
279  return array;
280 }
281 
282 
283 /*---------------------------------------------------------------------*
284  * Create/destroy sudoku *
285  *---------------------------------------------------------------------*/
300 L_SUDOKU *
301 sudokuCreate(l_int32 *array)
302 {
303 l_int32 i, val, locs_index;
304 L_SUDOKU *sud;
305 
306  PROCNAME("sudokuCreate");
307 
308  if (!array)
309  return (L_SUDOKU *)ERROR_PTR("array not defined", procName, NULL);
310 
311  locs_index = 0; /* into locs array */
312  sud = (L_SUDOKU *)LEPT_CALLOC(1, sizeof(L_SUDOKU));
313  sud->locs = (l_int32 *)LEPT_CALLOC(81, sizeof(l_int32));
314  sud->init = (l_int32 *)LEPT_CALLOC(81, sizeof(l_int32));
315  sud->state = (l_int32 *)LEPT_CALLOC(81, sizeof(l_int32));
316  for (i = 0; i < 81; i++) {
317  val = array[i];
318  sud->init[i] = val;
319  sud->state[i] = val;
320  if (val == 0)
321  sud->locs[locs_index++] = i;
322  }
323  sud->num = locs_index;
324  sud->failure = FALSE;
325  sud->finished = FALSE;
326  return sud;
327 }
328 
329 
336 void
338 {
339 L_SUDOKU *sud;
340 
341  PROCNAME("sudokuDestroy");
342 
343  if (psud == NULL) {
344  L_WARNING("ptr address is NULL\n", procName);
345  return;
346  }
347  if ((sud = *psud) == NULL)
348  return;
349 
350  LEPT_FREE(sud->locs);
351  LEPT_FREE(sud->init);
352  LEPT_FREE(sud->state);
353  LEPT_FREE(sud);
354 
355  *psud = NULL;
356  return;
357 }
358 
359 
360 /*---------------------------------------------------------------------*
361  * Solve the puzzle *
362  *---------------------------------------------------------------------*/
370 l_int32
372 {
373  PROCNAME("sudokuSolve");
374 
375  if (!sud)
376  return ERROR_INT("sud not defined", procName, 0);
377 
378  if (!sudokuValidState(sud->init))
379  return ERROR_INT("initial state not valid", procName, 0);
380 
381  while (1) {
382  if (sudokuNewGuess(sud))
383  break;
384  if (sud->finished == TRUE)
385  break;
386  }
387 
388  if (sud->failure == TRUE) {
389  fprintf(stderr, "Failure after %d guesses\n", sud->nguess);
390  return 0;
391  }
392 
393  fprintf(stderr, "Solved after %d guesses\n", sud->nguess);
394  return 1;
395 }
396 
397 
411 static l_int32
412 sudokuValidState(l_int32 *state)
413 {
414 l_int32 i;
415 
416  PROCNAME("sudokuValidState");
417 
418  if (!state)
419  return ERROR_INT("state not defined", procName, 0);
420 
421  for (i = 0; i < 81; i++) {
422  if (!sudokuTestState(state, i))
423  return 0;
424  }
425 
426  return 1;
427 }
428 
429 
448 static l_int32
450 {
451 l_int32 index, val, valid;
452 l_int32 *locs, *state;
453 
454  locs = sud->locs;
455  state = sud->state;
456  index = locs[sud->current]; /* 0 to 80 */
457  val = state[index];
458  if (val == 9) { /* backtrack or give up */
459  if (sud->current == 0) {
460  sud->failure = TRUE;
461  return 1;
462  }
463  state[index] = 0;
464  sud->current--;
465  } else { /* increment current value and test */
466  sud->nguess++;
467  state[index]++;
468  valid = sudokuTestState(state, index);
469  if (valid) {
470  if (sud->current == sud->num - 1) { /* we're done */
471  sud->finished = TRUE;
472  return 0;
473  } else { /* advance to next position */
474  sud->current++;
475  }
476  }
477  }
478 
479  return 0;
480 }
481 
482 
490 static l_int32
491 sudokuTestState(l_int32 *state,
492  l_int32 index)
493 {
494 l_int32 i, j, val, row, rowstart, rowend, col;
495 l_int32 blockrow, blockcol, blockstart, rowindex, locindex;
496 
497  if ((val = state[index]) == 0) /* automatically valid */
498  return 1;
499 
500  /* Test row. Test val is at (x, y) = (index % 9, index / 9) */
501  row = index / 9;
502  rowstart = 9 * row;
503  for (i = rowstart; i < index; i++) {
504  if (state[i] == val)
505  return 0;
506  }
507  rowend = rowstart + 9;
508  for (i = index + 1; i < rowend; i++) {
509  if (state[i] == val)
510  return 0;
511  }
512 
513  /* Test column */
514  col = index % 9;
515  for (j = col; j < index; j += 9) {
516  if (state[j] == val)
517  return 0;
518  }
519  for (j = index + 9; j < 81; j += 9) {
520  if (state[j] == val)
521  return 0;
522  }
523 
524  /* Test local 3x3 block */
525  blockrow = 3 * (row / 3);
526  blockcol = 3 * (col / 3);
527  blockstart = 9 * blockrow + blockcol;
528  for (i = 0; i < 3; i++) {
529  rowindex = blockstart + 9 * i;
530  for (j = 0; j < 3; j++) {
531  locindex = rowindex + j;
532  if (index == locindex) continue;
533  if (state[locindex] == val)
534  return 0;
535  }
536  }
537 
538  return 1;
539 }
540 
541 
542 /*---------------------------------------------------------------------*
543  * Test for uniqueness *
544  *---------------------------------------------------------------------*/
561 l_ok
562 sudokuTestUniqueness(l_int32 *array,
563  l_int32 *punique)
564 {
565 l_int32 same1, same2, same3;
566 l_int32 *array1, *array2, *array3;
567 L_SUDOKU *sud, *sud1, *sud2, *sud3;
568 
569  PROCNAME("sudokuTestUniqueness");
570 
571  if (!punique)
572  return ERROR_INT("&unique not defined", procName, 1);
573  *punique = 0;
574  if (!array)
575  return ERROR_INT("array not defined", procName, 1);
576 
577  sud = sudokuCreate(array);
578  sudokuSolve(sud);
579  array1 = sudokuRotateArray(array, 1);
580  sud1 = sudokuCreate(array1);
581  sudokuSolve(sud1);
582  array2 = sudokuRotateArray(array, 2);
583  sud2 = sudokuCreate(array2);
584  sudokuSolve(sud2);
585  array3 = sudokuRotateArray(array, 3);
586  sud3 = sudokuCreate(array3);
587  sudokuSolve(sud3);
588 
589  sudokuCompareState(sud, sud1, 1, &same1);
590  sudokuCompareState(sud, sud2, 2, &same2);
591  sudokuCompareState(sud, sud3, 3, &same3);
592  *punique = (same1 && same2 && same3);
593 
594  sudokuDestroy(&sud);
595  sudokuDestroy(&sud1);
596  sudokuDestroy(&sud2);
597  sudokuDestroy(&sud3);
598  LEPT_FREE(array1);
599  LEPT_FREE(array2);
600  LEPT_FREE(array3);
601  return 0;
602 }
603 
604 
622 static l_int32
624  L_SUDOKU *sud2,
625  l_int32 quads,
626  l_int32 *psame)
627 {
628 l_int32 i, same;
629 l_int32 *array;
630 
631  PROCNAME("sudokuCompareState");
632 
633  if (!psame)
634  return ERROR_INT("&same not defined", procName, 1);
635  *psame = 0;
636  if (!sud1)
637  return ERROR_INT("sud1 not defined", procName, 1);
638  if (!sud2)
639  return ERROR_INT("sud1 not defined", procName, 1);
640  if (quads < 1 || quads > 3)
641  return ERROR_INT("valid quads in {1,2,3}", procName, 1);
642 
643  same = TRUE;
644  if ((array = sudokuRotateArray(sud1->state, quads)) == NULL)
645  return ERROR_INT("array not made", procName, 1);
646  for (i = 0; i < 81; i++) {
647  if (array[i] != sud2->state[i]) {
648  same = FALSE;
649  break;
650  }
651  }
652  *psame = same;
653  LEPT_FREE(array);
654  return 0;
655 }
656 
657 
665 static l_int32 *
666 sudokuRotateArray(l_int32 *array,
667  l_int32 quads)
668 {
669 l_int32 i, j, sindex, dindex;
670 l_int32 *rarray;
671 
672  PROCNAME("sudokuRotateArray");
673 
674  if (!array)
675  return (l_int32 *)ERROR_PTR("array not defined", procName, NULL);
676  if (quads < 1 || quads > 3)
677  return (l_int32 *)ERROR_PTR("valid quads in {1,2,3}", procName, NULL);
678 
679  rarray = (l_int32 *)LEPT_CALLOC(81, sizeof(l_int32));
680  if (quads == 1) {
681  for (j = 0, dindex = 0; j < 9; j++) {
682  for (i = 8; i >= 0; i--) {
683  sindex = 9 * i + j;
684  rarray[dindex++] = array[sindex];
685  }
686  }
687  } else if (quads == 2) {
688  for (i = 8, dindex = 0; i >= 0; i--) {
689  for (j = 8; j >= 0; j--) {
690  sindex = 9 * i + j;
691  rarray[dindex++] = array[sindex];
692  }
693  }
694  } else { /* quads == 3 */
695  for (j = 8, dindex = 0; j >= 0; j--) {
696  for (i = 0; i < 9; i++) {
697  sindex = 9 * i + j;
698  rarray[dindex++] = array[sindex];
699  }
700  }
701  }
702 
703  return rarray;
704 }
705 
706 
707 /*---------------------------------------------------------------------*
708  * Generation *
709  *---------------------------------------------------------------------*/
730 L_SUDOKU *
731 sudokuGenerate(l_int32 *array,
732  l_int32 seed,
733  l_int32 minelems,
734  l_int32 maxtries)
735 {
736 l_int32 index, sector, nzeros, removefirst, tries, val, oldval, unique;
737 L_SUDOKU *sud, *testsud;
738 
739  PROCNAME("sudokuGenerate");
740 
741  if (!array)
742  return (L_SUDOKU *)ERROR_PTR("array not defined", procName, NULL);
743  if (minelems > 80)
744  return (L_SUDOKU *)ERROR_PTR("minelems must be < 81", procName, NULL);
745 
746  /* Remove up to 30 numbers at random from the solution.
747  * Test if the solution is valid -- the initial 'solution' may
748  * have been invalid. Then test if the sudoku with 30 zeroes
749  * is unique -- it almost always will be. */
750  srand(seed);
751  nzeros = 0;
752  sector = 0;
753  removefirst = L_MIN(30, 81 - minelems);
754  while (nzeros < removefirst) {
755  genRandomIntegerInRange(9, 0, &val);
756  index = 27 * (sector / 3) + 3 * (sector % 3) +
757  9 * (val / 3) + (val % 3);
758  if (array[index] == 0) continue;
759  array[index] = 0;
760  nzeros++;
761  sector++;
762  sector %= 9;
763  }
764  testsud = sudokuCreate(array);
765  sudokuSolve(testsud);
766  if (testsud->failure) {
767  sudokuDestroy(&testsud);
768  L_ERROR("invalid initial solution\n", procName);
769  return NULL;
770  }
771  sudokuTestUniqueness(testsud->init, &unique);
772  sudokuDestroy(&testsud);
773  if (!unique) {
774  L_ERROR("non-unique result with 30 zeroes\n", procName);
775  return NULL;
776  }
777 
778  /* Remove more numbers, testing at each removal for uniqueness. */
779  tries = 0;
780  sector = 0;
781  while (1) {
782  if (tries > maxtries) break;
783  if (81 - nzeros <= minelems) break;
784 
785  if (tries == 0) {
786  fprintf(stderr, "Trying %d zeros\n", nzeros);
787  tries = 1;
788  }
789 
790  /* Choose an element to be zeroed. We choose one
791  * at random in succession from each of the nine sectors. */
792  genRandomIntegerInRange(9, 0, &val);
793  index = 27 * (sector / 3) + 3 * (sector % 3) +
794  9 * (val / 3) + (val % 3);
795  sector++;
796  sector %= 9;
797  if (array[index] == 0) continue;
798 
799  /* Save the old value in case we need to revert */
800  oldval = array[index];
801 
802  /* Is there a solution? If not, try again. */
803  array[index] = 0;
804  testsud = sudokuCreate(array);
805  sudokuSolve(testsud);
806  if (testsud->failure == TRUE) {
807  sudokuDestroy(&testsud);
808  array[index] = oldval; /* revert */
809  tries++;
810  continue;
811  }
812 
813  /* Is the solution unique? If not, try again. */
814  sudokuTestUniqueness(testsud->init, &unique);
815  sudokuDestroy(&testsud);
816  if (!unique) { /* revert and try again */
817  array[index] = oldval;
818  tries++;
819  } else { /* accept this */
820  tries = 0;
821  fprintf(stderr, "Have %d zeros\n", nzeros);
822  nzeros++;
823  }
824  }
825  fprintf(stderr, "Final: nelems = %d\n", 81 - nzeros);
826 
827  /* Show that we can recover the solution */
828  sud = sudokuCreate(array);
829  sudokuOutput(sud, L_SUDOKU_INIT);
830  sudokuSolve(sud);
831  sudokuOutput(sud, L_SUDOKU_STATE);
832 
833  return sud;
834 }
835 
836 
837 /*---------------------------------------------------------------------*
838  * Output *
839  *---------------------------------------------------------------------*/
853 l_int32
855  l_int32 arraytype)
856 {
857 l_int32 i, j;
858 l_int32 *array;
859 
860  PROCNAME("sudokuOutput");
861 
862  if (!sud)
863  return ERROR_INT("sud not defined", procName, 1);
864  if (arraytype == L_SUDOKU_INIT)
865  array = sud->init;
866  else if (arraytype == L_SUDOKU_STATE)
867  array = sud->state;
868  else
869  return ERROR_INT("invalid arraytype", procName, 1);
870 
871  for (i = 0; i < 9; i++) {
872  for (j = 0; j < 9; j++)
873  fprintf(stderr, "%d ", array[9 * i + j]);
874  fprintf(stderr, "\n");
875  }
876 
877  return 0;
878 }
static l_int32 sudokuCompareState(L_SUDOKU *sud1, L_SUDOKU *sud2, l_int32 quads, l_int32 *psame)
sudokuCompareState()
Definition: sudoku.c:623
l_ok genRandomIntegerInRange(l_int32 range, l_int32 seed, l_int32 *pval)
genRandomIntegerInRange()
Definition: utils1.c:510
l_int32 num
Definition: sudoku.h:54
l_int32 * state
Definition: sudoku.h:59
Definition: pix.h:716
static l_int32 sudokuNewGuess(L_SUDOKU *sud)
sudokuNewGuess()
Definition: sudoku.c:449
l_int32 nguess
Definition: sudoku.h:61
SARRAY * sarrayCreate(l_int32 n)
sarrayCreate()
Definition: sarray1.c:163
Definition: array.h:116
l_uint8 * l_binaryRead(const char *filename, size_t *pnbytes)
l_binaryRead()
Definition: utils2.c:1212
L_SUDOKU * sudokuGenerate(l_int32 *array, l_int32 seed, l_int32 minelems, l_int32 maxtries)
sudokuGenerate()
Definition: sudoku.c:731
l_int32 sudokuSolve(L_SUDOKU *sud)
sudokuSolve()
Definition: sudoku.c:371
l_ok sarrayAddString(SARRAY *sa, const char *string, l_int32 copyflag)
sarrayAddString()
Definition: sarray1.c:446
l_int32 failure
Definition: sudoku.h:63
l_int32 finished
Definition: sudoku.h:62
char * sarrayGetString(SARRAY *sa, l_int32 index, l_int32 copyflag)
sarrayGetString()
Definition: sarray1.c:681
l_ok sudokuTestUniqueness(l_int32 *array, l_int32 *punique)
sudokuTestUniqueness()
Definition: sudoku.c:562
SARRAY * sarrayCreateLinesFromString(const char *string, l_int32 blankflag)
sarrayCreateLinesFromString()
Definition: sarray1.c:276
static l_int32 sudokuValidState(l_int32 *state)
sudokuValidState()
Definition: sudoku.c:412
static l_int32 * sudokuRotateArray(l_int32 *array, l_int32 quads)
sudokuRotateArray()
Definition: sudoku.c:666
l_int32 * sudokuReadFile(const char *filename)
sudokuReadFile()
Definition: sudoku.c:181
l_int32 sudokuOutput(L_SUDOKU *sud, l_int32 arraytype)
sudokuOutput()
Definition: sudoku.c:854
l_int32 sarrayGetCount(SARRAY *sa)
sarrayGetCount()
Definition: sarray1.c:621
static l_int32 sudokuTestState(l_int32 *state, l_int32 index)
sudokuTestState()
Definition: sudoku.c:491
l_int32 * sudokuReadString(const char *str)
sudokuReadString()
Definition: sudoku.c:260
Definition: pix.h:718
l_int32 * locs
Definition: sudoku.h:55
void sudokuDestroy(L_SUDOKU **psud)
sudokuDestroy()
Definition: sudoku.c:337
L_SUDOKU * sudokuCreate(l_int32 *array)
sudokuCreate()
Definition: sudoku.c:301
l_int32 * init
Definition: sudoku.h:57
SARRAY * sarrayCreateWordsFromString(const char *string)
sarrayCreateWordsFromString()
Definition: sarray1.c:226
void sarrayDestroy(SARRAY **psa)
sarrayDestroy()
Definition: sarray1.c:355
SARRAY * data
Definition: stringcode.h:45
l_int32 current
Definition: sudoku.h:56