Leptonica 1.68
C Image Processing Library

sudoku.c

Go to the documentation of this file.
00001 /*====================================================================*
00002  -  Copyright (C) 2001 Leptonica.  All rights reserved.
00003  -  This software is distributed in the hope that it will be
00004  -  useful, but with NO WARRANTY OF ANY KIND.
00005  -  No author or distributor accepts responsibility to anyone for the
00006  -  consequences of using this software, or for whether it serves any
00007  -  particular purpose or works at all, unless he or she says so in
00008  -  writing.  Everyone is granted permission to copy, modify and
00009  -  redistribute this source code, for commercial or non-commercial
00010  -  purposes, with the following restrictions: (1) the origin of this
00011  -  source code must not be misrepresented; (2) modified versions must
00012  -  be plainly marked as such; and (3) this notice may not be removed
00013  -  or altered from any source or modified source distribution.
00014  *====================================================================*/
00015 
00016 
00017 /*
00018  *  sudoku.c
00019  *
00020  *      Solve a sudoku by brute force search
00021  *
00022  *      Read input data from file or string
00023  *          l_int32         *sudokuReadFile()
00024  *          l_int32         *sudokuReadString()
00025  *
00026  *      Create/destroy
00027  *          L_SUDOKU        *sudokuCreate()
00028  *          void             sudokuDestroy()
00029  *
00030  *      Solve the puzzle
00031  *          l_int32          sudokuSolve()
00032  *          static l_int32   sudokuValidState()
00033  *          static l_int32   sudokuNewGuess()
00034  *          static l_int32   sudokuTestState()
00035  *
00036  *      Test for uniqueness
00037  *          l_int32          sudokuTestUniqueness()
00038  *          static l_int32   sudokuCompareState()
00039  *          static l_int32  *sudokuRotateArray()
00040  *
00041  *      Generation
00042  *          L_SUDOKU        *sudokuGenerate()
00043  *
00044  *      Output
00045  *          l_int32          sudokuOutput()
00046  *
00047  *  Solving sudokus is a somewhat addictive pastime.  The rules are
00048  *  simple but it takes just enough concentration to make it rewarding
00049  *  when you find a number.  And you get 50 to 60 such rewards each time
00050  *  you complete one.  The downside is that you could have been doing
00051  *  something more creative, like keying out a new plant, staining
00052  *  the deck, or even writing a computer program to discourage your
00053  *  wife from doing sudokus.
00054  *
00055  *  My original plan for the sudoku solver was somewhat grandiose.
00056  *  The program would model the way a person solves the problem.
00057  *  It would examine each empty position and determine how many possible
00058  *  numbers could fit.  The empty positions would be entered in a priority
00059  *  queue keyed on the number of possible numbers that could fit.
00060  *  If there existed a position where only a single number would work,
00061  *  it would greedily take it.  Otherwise it would consider a
00062  *  positions that could accept two and make a guess, with backtracking
00063  *  if an impossible state were reached.  And so on.
00064  *
00065  *  Then one of my colleagues announced she had solved the problem
00066  *  by brute force and it was fast.  At that point the original plan was
00067  *  dead in the water, because the two top requirements for a leptonica
00068  *  algorithm are (1) as simple as possible and (2) fast.  The brute
00069  *  force approach starts at the UL corner, and in succession at each
00070  *  blank position it finds the first valid number (testing in
00071  *  sequence from 1 to 9).  When no number will fit a blank position
00072  *  it backtracks, choosing the next valid number in the previous
00073  *  blank position.
00074  *
00075  *  This is an inefficient method for pruning the space of solutions
00076  *  (imagine backtracking from the LR corner back to the UL corner
00077  *  and starting over with a new guess), but it nevertheless gets
00078  *  the job done quickly.  I have made no effort to optimize
00079  *  it, because it is fast: a 5-star (highest difficulty) sudoku might
00080  *  require a million guesses and take 0.05 sec.  (This BF implementation
00081  *  does about 20M guesses/sec at 3 GHz.)
00082  *
00083  *  Proving uniqueness of a sudoku solution is tricker than finding
00084  *  a solution (or showing that no solution exists).  A good indication
00085  *  that a solution is unique is if we get the same result solving
00086  *  by brute force when the puzzle is also rotated by 90, 180 and 270
00087  *  degrees.  If there are multiple solutions, it seems unlikely
00088  *  that you would get the same solution four times in a row, using a
00089  *  brute force method that increments guesses and scans LR/TB.
00090  *  The function sudokuTestUniqueness() does this.
00091  *
00092  *  And given a function that can determine uniqueness, it is
00093  *  easy to generate valid sudokus.  We provide sudokuGenerate(),
00094  *  which starts with some valid initial solution, and randomly
00095  *  removes numbers, stopping either when a minimum number of non-zero
00096  *  elements are left, or when it becomes difficult to remove another
00097  *  element without destroying the uniqueness of the solution.
00098  *
00099  *  For further reading, see the Wikipedia articles:
00100  *     (1) http://en.wikipedia.org/wiki/Algorithmics_of_sudoku
00101  *     (2) http://en.wikipedia.org/wiki/Sudoku
00102  *
00103  *  How many 9x9 sudokus are there?  Here are the numbers.
00104  *   - From ref(1), there are about 6 x 10^27 "latin squares", where
00105  *     each row and column has all 9 digits.
00106  *   - There are 7.2 x 10^21 actual solutions, having the added
00107  *     constraint in each of the 9 3x3 squares.  (The constraint
00108  *     reduced the number by the fraction 1.2 x 10^(-6).)
00109  *   - There are a mere 5.5 billion essentially different solutions (EDS),
00110  *     when symmetries (rotation, reflection, permutation and relabelling)
00111  *     are removed.
00112  *   - Thus there are 1.3 x 10^12 solutions that can be derived by
00113  *     symmetry from each EDS.  Can we account for these?
00114  *   - Sort-of.  From an EDS, you can derive (3!)^8 = 1.7 million solutions
00115  *     by simply permuting rows and columns.  (Do you see why it is
00116  *     not (3!)^6 ?)
00117  *   - Also from an EDS, you can derive 9! solutions by relabelling,
00118  *     and 4 solutions by rotation, for a total of 1.45 million solutions
00119  *     by relabelling and rotation.  Then taking the product, by symmetry
00120  *     we can derive 1.7M x 1.45M = 2.45 trillion solutions from each EDS.
00121  *     (Something is off by about a factor of 2 -- close enough.)
00122  *
00123  *  Another interesting fact is that there are apparently 48K EDS sudokus
00124  *  (with unique solutions) that have only 17 givens.  No sudokus are known
00125  *  with less than 17, but there exists no proof that this is the minimum.
00126  */
00127 
00128 #include "allheaders.h"
00129 
00130 
00131 static l_int32 sudokuValidState(l_int32  *state);
00132 static l_int32 sudokuNewGuess(L_SUDOKU  *sud);
00133 static l_int32 sudokuTestState(l_int32  *state, l_int32  index);
00134 static l_int32 sudokuCompareState(L_SUDOKU  *sud1, L_SUDOKU  *sud2,
00135                                   l_int32  quads, l_int32  *psame);
00136 static l_int32 *sudokuRotateArray(l_int32  *array, l_int32  quads);
00137 
00138     /* An example of a valid solution */
00139 static const char valid_solution[] = "3 8 7 2 6 4 1 9 5 "
00140                                      "2 6 5 8 9 1 4 3 7 "
00141                                      "1 4 9 5 3 7 6 8 2 "
00142                                      "5 2 3 7 1 6 8 4 9 "
00143                                      "7 1 6 9 4 8 2 5 3 "
00144                                      "8 9 4 3 5 2 7 1 6 "
00145                                      "9 7 2 1 8 5 3 6 4 "
00146                                      "4 3 1 6 7 9 5 2 8 "
00147                                      "6 5 8 4 2 3 9 7 1 ";
00148 
00149 
00150 /*---------------------------------------------------------------------*
00151  *               Read input data from file or string                   *
00152  *---------------------------------------------------------------------*/
00153 /*!
00154  *  sudokuReadFile()
00155  *
00156  *      Input:  filename (of formatted sudoku file)
00157  *      Return: array (of 81 numbers), or null on error
00158  *
00159  *  Notes:
00160  *      (1) The file format has:
00161  *          * any number of comment lines beginning with '#'
00162  *          * a set of 9 lines, each having 9 digits (0-9) separated
00163  *            by a space
00164  */
00165 l_int32 *
00166 sudokuReadFile(const char  *filename)
00167 {
00168 char     *str, *strj;
00169 l_uint8  *data;
00170 l_int32   i, j, nlines, val, index, error;
00171 l_int32  *array;
00172 size_t    size;
00173 SARRAY   *saline, *sa1, *sa2;
00174 
00175     PROCNAME("sudokuReadFile");
00176 
00177     if (!filename)
00178         return (l_int32 *)ERROR_PTR("filename not defined", procName, NULL);
00179     data = l_binaryRead(filename, &size);
00180     sa1 = sarrayCreateLinesFromString((char *)data, 0);
00181     sa2 = sarrayCreate(9);
00182 
00183         /* Filter out the comment lines; verify that there are 9 data lines */
00184     nlines = sarrayGetCount(sa1);
00185     for (i = 0; i < nlines; i++) {
00186         str = sarrayGetString(sa1, i, L_NOCOPY);
00187         if (str[0] != '#')
00188             sarrayAddString(sa2, str, L_COPY);
00189     }
00190     FREE(data);
00191     sarrayDestroy(&sa1);
00192     nlines = sarrayGetCount(sa2);
00193     if (nlines != 9) {
00194         sarrayDestroy(&sa2);
00195         L_ERROR_INT("file has %d lines", procName, nlines);
00196         return (l_int32 *)ERROR_PTR("invalid file", procName, NULL);
00197     }
00198 
00199         /* Read the data into the array, verifying that each data
00200          * line has 9 numbers. */
00201     error = FALSE;
00202     array = (l_int32 *)CALLOC(81, sizeof(l_int32));
00203     for (i = 0, index = 0; i < 9; i++) {
00204         str = sarrayGetString(sa2, i, L_NOCOPY);
00205         saline = sarrayCreateWordsFromString(str);
00206         if (sarrayGetCount(saline) != 9) {
00207             error = TRUE;
00208             sarrayDestroy(&saline);
00209             break;
00210         }
00211         for (j = 0; j < 9; j++) {
00212             strj = sarrayGetString(saline, j, L_NOCOPY);
00213             if (sscanf(strj, "%d", &val) != 1)
00214                 error = TRUE;
00215             else
00216                 array[index++] = val;
00217         }
00218         sarrayDestroy(&saline);
00219         if (error) break;
00220     }
00221     sarrayDestroy(&sa2);
00222 
00223     if (error) {
00224         FREE(array);
00225         return (l_int32 *)ERROR_PTR("invalid data", procName, NULL);
00226     }
00227 
00228     return array;
00229 }
00230 
00231 
00232 /*!
00233  *  sudokuReadString()
00234  *
00235  *      Input:  str (of input data)
00236  *      Return: array (of 81 numbers), or null on error
00237  *
00238  *  Notes:
00239  *      (1) The string is formatted as 81 single digits, each separated
00240  *          by 81 spaces.
00241  */
00242 l_int32 *
00243 sudokuReadString(const char  *str)
00244 {
00245 l_int32   i;
00246 l_int32  *array;
00247 
00248     PROCNAME("sudokuReadString");
00249 
00250     if (!str)
00251         return (l_int32 *)ERROR_PTR("str not defined", procName, NULL);
00252 
00253         /* Read in the initial solution */
00254     array = (l_int32 *)CALLOC(81, sizeof(l_int32));
00255     for (i = 0; i < 81; i++) {
00256         if (sscanf(str + 2 * i, "%d ", &array[i]) != 1)
00257             return (l_int32 *)ERROR_PTR("invalid format", procName, NULL);
00258     }
00259 
00260     return array;
00261 }
00262 
00263 
00264 /*---------------------------------------------------------------------*
00265  *                        Create/destroy sudoku                        *
00266  *---------------------------------------------------------------------*/
00267 /*!
00268  *  sudokuCreate()
00269  *
00270  *      Input:  array (of 81 numbers, 9 rows of 9 numbers each)
00271  *      Return: l_sudoku, or null on error
00272  *
00273  *  Notes:
00274  *      (1) The input array has 0 for the unknown values, and 1-9
00275  *          for the known initial values.  It is generated from
00276  *          a file using sudokuReadInput(), which checks that the file
00277  *          data has 81 numbers in 9 rows.
00278  */
00279 L_SUDOKU *
00280 sudokuCreate(l_int32  *array)
00281 {
00282 l_int32    i, val, locs_index;
00283 L_SUDOKU  *sud;
00284 
00285     PROCNAME("sudokuCreate");
00286 
00287     if (!array)
00288         return (L_SUDOKU *)ERROR_PTR("array not defined", procName, NULL);
00289 
00290     locs_index = 0;  /* into locs array */
00291     if ((sud = (L_SUDOKU *)CALLOC(1, sizeof(L_SUDOKU))) == NULL)
00292         return (L_SUDOKU *)ERROR_PTR("sud not made", procName, NULL);
00293     if ((sud->locs = (l_int32 *)CALLOC(81, sizeof(l_int32))) == NULL)
00294         return (L_SUDOKU *)ERROR_PTR("su state array not made", procName, NULL);
00295     if ((sud->init = (l_int32 *)CALLOC(81, sizeof(l_int32))) == NULL)
00296         return (L_SUDOKU *)ERROR_PTR("su init array not made", procName, NULL);
00297     if ((sud->state = (l_int32 *)CALLOC(81, sizeof(l_int32))) == NULL)
00298         return (L_SUDOKU *)ERROR_PTR("su state array not made", procName, NULL);
00299     for (i = 0; i < 81; i++) {
00300         val = array[i];
00301         sud->init[i] = val;
00302         sud->state[i] = val;
00303         if (val == 0)
00304             sud->locs[locs_index++] = i;
00305     }
00306     sud->num = locs_index;
00307     sud->failure = FALSE;
00308     sud->finished = FALSE;
00309     return sud;
00310 }
00311 
00312 
00313 /*!
00314  *  sudokuDestroy()
00315  *
00316  *      Input:  &l_sudoku (<to be nulled>)
00317  *      Return: void
00318  */
00319 void
00320 sudokuDestroy(L_SUDOKU  **psud)
00321 {
00322 L_SUDOKU  *sud;
00323 
00324     PROCNAME("sudokuDestroy");
00325 
00326     if (psud == NULL) {
00327         L_WARNING("ptr address is NULL", procName);
00328         return;
00329     }
00330     if ((sud = *psud) == NULL)
00331         return;
00332 
00333     FREE(sud->locs);
00334     FREE(sud->init);
00335     FREE(sud->state);
00336     FREE(sud);
00337 
00338     *psud = NULL;
00339     return;
00340 }
00341 
00342 
00343 /*---------------------------------------------------------------------*
00344  *                           Solve the puzzle                          *
00345  *---------------------------------------------------------------------*/
00346 /*!
00347  *  sudokuSolve()
00348  *
00349  *      Input:  l_sudoku (starting in initial state)
00350  *      Return: 1 on success, 0 on failure to solve (note reversal of
00351  *              typical unix returns)
00352  */
00353 l_int32
00354 sudokuSolve(L_SUDOKU  *sud)
00355 {
00356     PROCNAME("sudokuSolve");
00357 
00358     if (!sud)
00359         return ERROR_INT("sud not defined", procName, 0);
00360 
00361     if (!sudokuValidState(sud->init))
00362         return ERROR_INT("initial state not valid", procName, 0);
00363 
00364     while (1) {
00365         if (sudokuNewGuess(sud))
00366             break;
00367         if (sud->finished == TRUE)
00368             break;
00369     }
00370 
00371     if (sud->failure == TRUE) {
00372         fprintf(stderr, "Failure after %d guesses\n", sud->nguess);
00373         return 0;
00374     }
00375 
00376     fprintf(stderr, "Solved after %d guesses\n", sud->nguess);
00377     return 1;
00378 }
00379 
00380 
00381 /*!
00382  *  sudokuValidState()
00383  *
00384  *      Input:  state (array of size 81)
00385  *      Return: 1 if valid, 0 if invalid
00386  *
00387  *  Notes:
00388  *      (1) This can be used on either the initial state (init)
00389  *          or on the current state (state) of the l_soduku.
00390  *          All values of 0 are ignored.
00391  */
00392 static l_int32
00393 sudokuValidState(l_int32  *state)
00394 {
00395 l_int32  i;
00396 
00397     PROCNAME("sudokuValidState");
00398 
00399     if (!state)
00400         return ERROR_INT("state not defined", procName, 0);
00401 
00402     for (i = 0; i < 81; i++) {
00403         if (!sudokuTestState(state, i))
00404             return 0;
00405     }
00406 
00407     return 1;
00408 }
00409 
00410 
00411 /*!
00412  *  sudokuNewGuess()
00413  *
00414  *      Input:  l_sudoku
00415  *      Return: 0 if OK; 1 if no solution is possible
00416  *
00417  *  Notes:
00418  *      (1) This attempts to increment the number in the current
00419  *          location.  If it can't, it backtracks (sets the number
00420  *          in the current location to zero and decrements the
00421  *          current location).  If it can, it tests that number,
00422  *          and if the number is valid, moves forward to the next
00423  *          empty location (increments the current location).
00424  *      (2) If there is no solution, backtracking will eventually
00425  *          exhaust possibilities for the first location.
00426  */
00427 static l_int32
00428 sudokuNewGuess(L_SUDOKU  *sud)
00429 {
00430 l_int32   index, val, valid;
00431 l_int32  *locs, *state;
00432 
00433     locs = sud->locs;
00434     state = sud->state;
00435     index = locs[sud->current];  /* 0 to 80 */
00436     val = state[index];
00437     if (val == 9) {  /* backtrack or give up */
00438         if (sud->current == 0) {
00439             sud->failure = TRUE;
00440             return 1;
00441         }
00442         state[index] = 0;
00443         sud->current--;
00444     }
00445     else {  /* increment current value and test */
00446         sud->nguess++;
00447         state[index]++;
00448         valid = sudokuTestState(state, index);
00449         if (valid) {
00450             if (sud->current == sud->num - 1) {  /* we're done */
00451                 sud->finished = TRUE;
00452                 return 0;
00453             }
00454             else  /* advance to next position */
00455                 sud->current++;
00456         }
00457     }
00458 
00459     return 0;
00460 }
00461 
00462 
00463 /*!
00464  *  sudokuTestState()
00465  *
00466  *      Input:  state (current state: array of 81 values)
00467  *              index (into state element that we are testing)
00468  *      Return: 1 if valid; 0 if invalid (no error checking)
00469  */
00470 static l_int32
00471 sudokuTestState(l_int32  *state,
00472                 l_int32   index)
00473 {
00474 l_int32  i, j, val, row, rowstart, rowend, col;
00475 l_int32  blockrow, blockcol, blockstart, rowindex, locindex;
00476 
00477     if ((val = state[index]) == 0)  /* automatically valid */
00478         return 1;
00479 
00480         /* Test row.  Test val is at (x, y) = (index % 9, index / 9)  */
00481     row = index / 9;
00482     rowstart = 9 * row;
00483     for (i = rowstart; i < index; i++) {
00484         if (state[i] == val)
00485             return 0;
00486     }
00487     rowend = rowstart + 9;
00488     for (i = index + 1; i < rowend; i++) {
00489         if (state[i] == val)
00490             return 0;
00491     }
00492 
00493         /* Test column */
00494     col = index % 9;
00495     for (j = col; j < index; j += 9) {
00496         if (state[j] == val)
00497             return 0;
00498     }
00499     for (j = index + 9; j < 81; j += 9) {
00500         if (state[j] == val)
00501             return 0;
00502     }
00503 
00504         /* Test local 3x3 block */
00505     blockrow = 3 * (row / 3);
00506     blockcol = 3 * (col / 3);
00507     blockstart = 9 * blockrow + blockcol;
00508     for (i = 0; i < 3; i++) {
00509         rowindex = blockstart + 9 * i;
00510         for (j = 0; j < 3; j++) {
00511             locindex = rowindex + j;
00512             if (index == locindex) continue;
00513             if (state[locindex] == val)
00514                 return 0;
00515         }
00516     }
00517 
00518     return 1;
00519 }
00520 
00521 
00522 /*---------------------------------------------------------------------*
00523  *                         Test for uniqueness                         *
00524  *---------------------------------------------------------------------*/
00525 /*!
00526  *  sudokuTestUniqueness()
00527  *
00528  *      Input:  array (of 81 numbers, 9 lines of 9 numbers each)
00529  *              &punique (<return> 1 if unique, 0 if not)
00530  *      Return: 0 if OK, 1 on error
00531  *
00532  *  Notes:
00533  *      (1) This applies the brute force method to all four 90 degree
00534  *          rotations.  If there is more than one solution, it is highly
00535  *          unlikely that all four results will be the same;
00536  *          consequently, if they are the same, the solution is
00537  *          most likely to be unique.
00538  */
00539 l_int32
00540 sudokuTestUniqueness(l_int32  *array,
00541                      l_int32  *punique)
00542 {
00543 l_int32    same1, same2, same3;
00544 l_int32   *array1, *array2, *array3;
00545 L_SUDOKU  *sud, *sud1, *sud2, *sud3;
00546 
00547     PROCNAME("sudokuTestUniqueness");
00548 
00549     if (!punique)
00550         return ERROR_INT("&unique not defined", procName, 1);
00551     *punique = 0;
00552     if (!array)
00553         return ERROR_INT("array not defined", procName, 1);
00554 
00555     sud = sudokuCreate(array);
00556     sudokuSolve(sud);
00557     array1 = sudokuRotateArray(array, 1);
00558     sud1 = sudokuCreate(array1);
00559     sudokuSolve(sud1);
00560     array2 = sudokuRotateArray(array, 2);
00561     sud2 = sudokuCreate(array2);
00562     sudokuSolve(sud2);
00563     array3 = sudokuRotateArray(array, 3);
00564     sud3 = sudokuCreate(array3);
00565     sudokuSolve(sud3);
00566 
00567     sudokuCompareState(sud, sud1, 1, &same1);
00568     sudokuCompareState(sud, sud2, 2, &same2);
00569     sudokuCompareState(sud, sud3, 3, &same3);
00570     *punique = (same1 && same2 && same3);
00571 
00572     sudokuDestroy(&sud);
00573     sudokuDestroy(&sud1);
00574     sudokuDestroy(&sud2);
00575     sudokuDestroy(&sud3);
00576     FREE(array1);
00577     FREE(array2);
00578     FREE(array3);
00579     return 0;
00580 }
00581 
00582 
00583 /*!
00584  *  sudokuCompareState()
00585  *
00586  *      Input:  sud1, sud2
00587  *              quads (rotation of sud2 input with respect to sud1,
00588  *                    in units of 90 degrees cw)
00589  *              &same (<return> 1 if all 4 results are identical; 0 otherwise)
00590  *      Return: 0 if OK, 1 on error
00591  *
00592  *  Notes:
00593  *      (1) The input to sud2 has been rotated by @quads relative to the
00594  *          input to sud1.  Therefore, we must rotate the solution to
00595  *          sud1 by the same amount before comparing it to the
00596  *          solution to sud2.
00597  */
00598 static l_int32
00599 sudokuCompareState(L_SUDOKU  *sud1,
00600                    L_SUDOKU  *sud2,
00601                    l_int32    quads,
00602                    l_int32   *psame)
00603 {
00604 l_int32   i, same;
00605 l_int32  *array;
00606 
00607     PROCNAME("sudokuCompareState");
00608 
00609     if (!psame)
00610         return ERROR_INT("&same not defined", procName, 1);
00611     *psame = 0;
00612     if (!sud1)
00613         return ERROR_INT("sud1 not defined", procName, 1);
00614     if (!sud2)
00615         return ERROR_INT("sud1 not defined", procName, 1);
00616     if (quads < 1 || quads > 3)
00617         return ERROR_INT("valid quads in {1,2,3}", procName, 1);
00618 
00619     same = TRUE;
00620     if ((array = sudokuRotateArray(sud1->state, quads)) == NULL)
00621         return ERROR_INT("array not made", procName, 1);
00622     for (i = 0; i < 81; i++) {
00623         if (array[i] != sud2->state[i]) {
00624             same = FALSE;
00625             break;
00626         }
00627     }
00628     *psame = same;
00629     FREE(array);
00630     return 0;
00631 }
00632 
00633 
00634 /*!
00635  *  sudokuRotateArray()
00636  *
00637  *      Input:  array (of 81 numbers; 9 lines of 9 numbers each)
00638  *              quads (1-3; number of 90 degree cw rotations)
00639  *      Return: rarray (rotated array), or null on error
00640  */
00641 static l_int32 *
00642 sudokuRotateArray(l_int32  *array,
00643                   l_int32   quads)
00644 {
00645 l_int32   i, j, sindex, dindex;
00646 l_int32  *rarray;
00647 
00648     PROCNAME("sudokuRotateArray");
00649 
00650     if (!array)
00651         return (l_int32 *)ERROR_PTR("array not defined", procName, NULL);
00652     if (quads < 1 || quads > 3)
00653         return (l_int32 *)ERROR_PTR("valid quads in {1,2,3}", procName, NULL);
00654 
00655     rarray = (l_int32 *)CALLOC(81, sizeof(l_int32));
00656     if (quads == 1) {
00657         for (j = 0, dindex = 0; j < 9; j++) {
00658              for (i = 8; i >= 0; i--) {
00659                  sindex = 9 * i + j;
00660                  rarray[dindex++] = array[sindex];
00661              }
00662         }
00663     }
00664     else if (quads == 2) {
00665         for (i = 8, dindex = 0; i >= 0; i--) {
00666              for (j = 8; j >= 0; j--) {
00667                  sindex = 9 * i + j;
00668                  rarray[dindex++] = array[sindex];
00669              }
00670         }
00671     }
00672     else {  /* quads == 3 */
00673         for (j = 8, dindex = 0; j >= 0; j--) {
00674              for (i = 0; i < 9; i++) {
00675                  sindex = 9 * i + j;
00676                  rarray[dindex++] = array[sindex];
00677              }
00678         }
00679     }
00680 
00681     return rarray;
00682 }
00683 
00684 
00685 /*---------------------------------------------------------------------*
00686  *                              Generation                             *
00687  *---------------------------------------------------------------------*/
00688 /*!
00689  *  sudokuGenerate()
00690  *
00691  *      Input:  array (of 81 numbers, 9 rows of 9 numbers each)
00692  *              seed (random number)
00693  *              minelems (min non-zero elements allowed; <= 80)
00694  *              maxtries (max tries to remove a number and get a valid sudoku)
00695  *      Return: l_sudoku, or null on error
00696  *
00697  *  Notes:
00698  *      (1) This is a brute force generator.  It starts with a completed
00699  *          sudoku solution and, by removing elements (setting them to 0),
00700  *          generates a valid (unique) sudoku initial condition.
00701  *      (2) The process stops when either @minelems, the minimum
00702  *          number of non-zero elements, is reached, or when the
00703  *          number of attempts to remove the next element exceeds @maxtries.
00704  *      (3) No sudoku is known with less than 17 nonzero elements.
00705  */
00706 L_SUDOKU *
00707 sudokuGenerate(l_int32  *array,
00708                l_int32   seed,
00709                l_int32   minelems,
00710                l_int32   maxtries)
00711 {
00712 l_int32    index, sector, nzeros, removefirst, tries, val, oldval, unique;
00713 L_SUDOKU  *sud, *testsud;
00714 
00715     PROCNAME("sudokuGenerate");
00716 
00717     if (!array)
00718         return (L_SUDOKU *)ERROR_PTR("array not defined", procName, NULL);
00719     if (minelems > 80)
00720         return (L_SUDOKU *)ERROR_PTR("minelems must be < 81", procName, NULL);
00721 
00722         /* Remove up to 30 numbers at random from the solution.
00723          * Test if the solution is valid -- the initial 'solution' may
00724          * have been invalid.  Then test if the sudoku with 30 zeroes
00725          * is unique -- it almost always will be. */
00726     srand(seed);
00727     nzeros = 0;
00728     sector = 0;
00729     removefirst = L_MIN(30, 81 - minelems);
00730     while (nzeros < removefirst) {
00731         genRandomIntegerInRange(9, 0, &val);
00732         index = 27 * (sector / 3) + 3 * (sector % 3) +
00733                 9 * (val / 3) + (val % 3);
00734         if (array[index] == 0) continue;
00735         array[index] = 0;
00736         nzeros++;
00737         sector++;
00738         sector %= 9;
00739     }
00740     testsud = sudokuCreate(array);
00741     sudokuSolve(testsud);
00742     if (testsud->failure) {
00743         sudokuDestroy(&testsud);
00744         L_ERROR("invalid initial solution", procName);
00745         return NULL;
00746     }
00747     sudokuTestUniqueness(testsud->init, &unique);
00748     sudokuDestroy(&testsud);
00749     if (!unique) {
00750         L_ERROR("non-unique result with 30 zeroes", procName);
00751         return NULL;
00752     }
00753 
00754         /* Remove more numbers, testing at each removal for uniqueness. */
00755     tries = 0;
00756     sector = 0;
00757     while (1) {
00758         if (tries > maxtries) break;
00759         if (81 - nzeros <= minelems) break;
00760 
00761         if (tries == 0) {
00762             fprintf(stderr, "Trying %d zeros\n", nzeros);
00763             tries = 1;
00764         }
00765 
00766             /* Choose an element to be zeroed.  We choose one
00767              * at random in succession from each of the nine sectors. */
00768         genRandomIntegerInRange(9, 0, &val);
00769         index = 27 * (sector / 3) + 3 * (sector % 3) +
00770                 9 * (val / 3) + (val % 3);
00771         sector++;
00772         sector %= 9;
00773         if (array[index] == 0) continue;
00774 
00775             /* Save the old value in case we need to revert */
00776         oldval = array[index];
00777 
00778             /* Is there a solution?  If not, try again. */
00779         array[index] = 0;
00780         testsud = sudokuCreate(array);
00781         sudokuSolve(testsud);
00782         if (testsud->failure == TRUE) {
00783             sudokuDestroy(&testsud);
00784             array[index] = oldval;  /* revert */
00785             tries++;
00786             continue;
00787         }
00788 
00789             /* Is the solution unique?  If not, try again. */
00790         sudokuTestUniqueness(testsud->init, &unique);
00791         sudokuDestroy(&testsud);
00792         if (!unique) {  /* revert and try again */
00793             array[index] = oldval;
00794             tries++;
00795         }
00796         else {  /* accept this */
00797             tries = 0;
00798             fprintf(stderr, "Have %d zeros\n", nzeros);
00799             nzeros++;
00800         }
00801     }
00802     fprintf(stderr, "Final: nelems = %d\n", 81 - nzeros);
00803 
00804         /* Show that we can recover the solution */
00805     sud = sudokuCreate(array);
00806     sudokuOutput(sud, L_SUDOKU_INIT);
00807     sudokuSolve(sud);
00808     sudokuOutput(sud, L_SUDOKU_STATE);
00809 
00810     return sud;
00811 }
00812 
00813 
00814 /*---------------------------------------------------------------------*
00815  *                               Output                                *
00816  *---------------------------------------------------------------------*/
00817 /*!
00818  *  sudokuOutput()
00819  *
00820  *      Input:  l_sudoku (at any stage)
00821  *              arraytype (L_SUDOKU_INIT, L_SUDOKU_STATE)
00822  *      Return: void
00823  *
00824  *  Notes:
00825  *      (1) Prints either the initial array or the current state
00826  *          of the solution.
00827  */
00828 l_int32
00829 sudokuOutput(L_SUDOKU  *sud,
00830              l_int32    arraytype)
00831 {
00832 l_int32   i, j;
00833 l_int32  *array;
00834 
00835     PROCNAME("sudokuOutput");
00836 
00837     if (!sud)
00838         return ERROR_INT("sud not defined", procName, 1);
00839     if (arraytype == L_SUDOKU_INIT)
00840         array = sud->init;
00841     else if (arraytype == L_SUDOKU_STATE)
00842         array = sud->state;
00843     else
00844         return ERROR_INT("invalid arraytype", procName, 1);
00845 
00846     for (i = 0; i < 9; i++) {
00847         for (j = 0; j < 9; j++)
00848             fprintf(stderr, "%d ", array[9 * i + j]);
00849         fprintf(stderr, "\n");
00850     }
00851 
00852     return 0;
00853 }
00854 
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Defines