chiark / gitweb /
I've changed my mind. For the benefit of users with slower
[sgt-puzzles.git] / solo.c
1 /*
2  * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
3  *
4  * TODO:
5  *
6  *  - it might still be nice to do some prioritisation on the
7  *    removal of numbers from the grid
8  *     + one possibility is to try to minimise the maximum number
9  *       of filled squares in any block, which in particular ought
10  *       to enforce never leaving a completely filled block in the
11  *       puzzle as presented.
12  *
13  *  - alternative interface modes
14  *     + sudoku.com's Windows program has a palette of possible
15  *       entries; you select a palette entry first and then click
16  *       on the square you want it to go in, thus enabling
17  *       mouse-only play. Useful for PDAs! I don't think it's
18  *       actually incompatible with the current highlight-then-type
19  *       approach: you _either_ highlight a palette entry and then
20  *       click, _or_ you highlight a square and then type. At most
21  *       one thing is ever highlighted at a time, so there's no way
22  *       to confuse the two.
23  *     + `pencil marks' might be useful for more subtle forms of
24  *       deduction, now we can create puzzles that require them.
25  */
26
27 /*
28  * Solo puzzles need to be square overall (since each row and each
29  * column must contain one of every digit), but they need not be
30  * subdivided the same way internally. I am going to adopt a
31  * convention whereby I _always_ refer to `r' as the number of rows
32  * of _big_ divisions, and `c' as the number of columns of _big_
33  * divisions. Thus, a 2c by 3r puzzle looks something like this:
34  *
35  *   4 5 1 | 2 6 3
36  *   6 3 2 | 5 4 1
37  *   ------+------     (Of course, you can't subdivide it the other way
38  *   1 4 5 | 6 3 2     or you'll get clashes; observe that the 4 in the
39  *   3 2 6 | 4 1 5     top left would conflict with the 4 in the second
40  *   ------+------     box down on the left-hand side.)
41  *   5 1 4 | 3 2 6
42  *   2 6 3 | 1 5 4
43  *
44  * The need for a strong naming convention should now be clear:
45  * each small box is two rows of digits by three columns, while the
46  * overall puzzle has three rows of small boxes by two columns. So
47  * I will (hopefully) consistently use `r' to denote the number of
48  * rows _of small boxes_ (here 3), which is also the number of
49  * columns of digits in each small box; and `c' vice versa (here
50  * 2).
51  *
52  * I'm also going to choose arbitrarily to list c first wherever
53  * possible: the above is a 2x3 puzzle, not a 3x2 one.
54  */
55
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <assert.h>
60 #include <ctype.h>
61 #include <math.h>
62
63 #ifdef STANDALONE_SOLVER
64 #include <stdarg.h>
65 int solver_show_working;
66 #endif
67
68 #include "puzzles.h"
69
70 #define max(x,y) ((x)>(y)?(x):(y))
71
72 /*
73  * To save space, I store digits internally as unsigned char. This
74  * imposes a hard limit of 255 on the order of the puzzle. Since
75  * even a 5x5 takes unacceptably long to generate, I don't see this
76  * as a serious limitation unless something _really_ impressive
77  * happens in computing technology; but here's a typedef anyway for
78  * general good practice.
79  */
80 typedef unsigned char digit;
81 #define ORDER_MAX 255
82
83 #define TILE_SIZE 32
84 #define BORDER 18
85
86 #define FLASH_TIME 0.4F
87
88 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF4 };
89
90 enum { DIFF_BLOCK, DIFF_SIMPLE, DIFF_INTERSECT,
91        DIFF_SET, DIFF_RECURSIVE, DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
92
93 enum {
94     COL_BACKGROUND,
95     COL_GRID,
96     COL_CLUE,
97     COL_USER,
98     COL_HIGHLIGHT,
99     NCOLOURS
100 };
101
102 struct game_params {
103     int c, r, symm, diff;
104 };
105
106 struct game_state {
107     int c, r;
108     digit *grid;
109     unsigned char *immutable;          /* marks which digits are clues */
110     int completed, cheated;
111 };
112
113 static game_params *default_params(void)
114 {
115     game_params *ret = snew(game_params);
116
117     ret->c = ret->r = 3;
118     ret->symm = SYMM_ROT2;             /* a plausible default */
119     ret->diff = DIFF_SIMPLE;           /* so is this */
120
121     return ret;
122 }
123
124 static void free_params(game_params *params)
125 {
126     sfree(params);
127 }
128
129 static game_params *dup_params(game_params *params)
130 {
131     game_params *ret = snew(game_params);
132     *ret = *params;                    /* structure copy */
133     return ret;
134 }
135
136 static int game_fetch_preset(int i, char **name, game_params **params)
137 {
138     static struct {
139         char *title;
140         game_params params;
141     } presets[] = {
142         { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK } },
143         { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE } },
144         { "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE } },
145         { "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT } },
146         { "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET } },
147         { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE } },
148         { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE } },
149     };
150
151     if (i < 0 || i >= lenof(presets))
152         return FALSE;
153
154     *name = dupstr(presets[i].title);
155     *params = dup_params(&presets[i].params);
156
157     return TRUE;
158 }
159
160 static game_params *decode_params(char const *string)
161 {
162     game_params *ret = default_params();
163
164     ret->c = ret->r = atoi(string);
165     ret->symm = SYMM_ROT2;
166     while (*string && isdigit((unsigned char)*string)) string++;
167     if (*string == 'x') {
168         string++;
169         ret->r = atoi(string);
170         while (*string && isdigit((unsigned char)*string)) string++;
171     }
172     while (*string) {
173         if (*string == 'r' || *string == 'm' || *string == 'a') {
174             int sn, sc;
175             sc = *string++;
176             sn = atoi(string);
177             while (*string && isdigit((unsigned char)*string)) string++;
178             if (sc == 'm' && sn == 4)
179                 ret->symm = SYMM_REF4;
180             if (sc == 'r' && sn == 4)
181                 ret->symm = SYMM_ROT4;
182             if (sc == 'r' && sn == 2)
183                 ret->symm = SYMM_ROT2;
184             if (sc == 'a')
185                 ret->symm = SYMM_NONE;
186         } else if (*string == 'd') {
187             string++;
188             if (*string == 't')        /* trivial */
189                 string++, ret->diff = DIFF_BLOCK;
190             else if (*string == 'b')   /* basic */
191                 string++, ret->diff = DIFF_SIMPLE;
192             else if (*string == 'i')   /* intermediate */
193                 string++, ret->diff = DIFF_INTERSECT;
194             else if (*string == 'a')   /* advanced */
195                 string++, ret->diff = DIFF_SET;
196         } else
197             string++;                  /* eat unknown character */
198     }
199
200     return ret;
201 }
202
203 static char *encode_params(game_params *params)
204 {
205     char str[80];
206
207     /*
208      * Symmetry is a game generation preference and hence is left
209      * out of the encoding. Users can add it back in as they see
210      * fit.
211      */
212     sprintf(str, "%dx%d", params->c, params->r);
213     return dupstr(str);
214 }
215
216 static config_item *game_configure(game_params *params)
217 {
218     config_item *ret;
219     char buf[80];
220
221     ret = snewn(5, config_item);
222
223     ret[0].name = "Columns of sub-blocks";
224     ret[0].type = C_STRING;
225     sprintf(buf, "%d", params->c);
226     ret[0].sval = dupstr(buf);
227     ret[0].ival = 0;
228
229     ret[1].name = "Rows of sub-blocks";
230     ret[1].type = C_STRING;
231     sprintf(buf, "%d", params->r);
232     ret[1].sval = dupstr(buf);
233     ret[1].ival = 0;
234
235     ret[2].name = "Symmetry";
236     ret[2].type = C_CHOICES;
237     ret[2].sval = ":None:2-way rotation:4-way rotation:4-way mirror";
238     ret[2].ival = params->symm;
239
240     ret[3].name = "Difficulty";
241     ret[3].type = C_CHOICES;
242     ret[3].sval = ":Trivial:Basic:Intermediate:Advanced";
243     ret[3].ival = params->diff;
244
245     ret[4].name = NULL;
246     ret[4].type = C_END;
247     ret[4].sval = NULL;
248     ret[4].ival = 0;
249
250     return ret;
251 }
252
253 static game_params *custom_params(config_item *cfg)
254 {
255     game_params *ret = snew(game_params);
256
257     ret->c = atoi(cfg[0].sval);
258     ret->r = atoi(cfg[1].sval);
259     ret->symm = cfg[2].ival;
260     ret->diff = cfg[3].ival;
261
262     return ret;
263 }
264
265 static char *validate_params(game_params *params)
266 {
267     if (params->c < 2 || params->r < 2)
268         return "Both dimensions must be at least 2";
269     if (params->c > ORDER_MAX || params->r > ORDER_MAX)
270         return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
271     return NULL;
272 }
273
274 /* ----------------------------------------------------------------------
275  * Full recursive Solo solver.
276  *
277  * The algorithm for this solver is shamelessly copied from a
278  * Python solver written by Andrew Wilkinson (which is GPLed, but
279  * I've reused only ideas and no code). It mostly just does the
280  * obvious recursive thing: pick an empty square, put one of the
281  * possible digits in it, recurse until all squares are filled,
282  * backtrack and change some choices if necessary.
283  *
284  * The clever bit is that every time it chooses which square to
285  * fill in next, it does so by counting the number of _possible_
286  * numbers that can go in each square, and it prioritises so that
287  * it picks a square with the _lowest_ number of possibilities. The
288  * idea is that filling in lots of the obvious bits (particularly
289  * any squares with only one possibility) will cut down on the list
290  * of possibilities for other squares and hence reduce the enormous
291  * search space as much as possible as early as possible.
292  *
293  * In practice the algorithm appeared to work very well; run on
294  * sample problems from the Times it completed in well under a
295  * second on my G5 even when written in Python, and given an empty
296  * grid (so that in principle it would enumerate _all_ solved
297  * grids!) it found the first valid solution just as quickly. So
298  * with a bit more randomisation I see no reason not to use this as
299  * my grid generator.
300  */
301
302 /*
303  * Internal data structure used in solver to keep track of
304  * progress.
305  */
306 struct rsolve_coord { int x, y, r; };
307 struct rsolve_usage {
308     int c, r, cr;                      /* cr == c*r */
309     /* grid is a copy of the input grid, modified as we go along */
310     digit *grid;
311     /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
312     unsigned char *row;
313     /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
314     unsigned char *col;
315     /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
316     unsigned char *blk;
317     /* This lists all the empty spaces remaining in the grid. */
318     struct rsolve_coord *spaces;
319     int nspaces;
320     /* If we need randomisation in the solve, this is our random state. */
321     random_state *rs;
322     /* Number of solutions so far found, and maximum number we care about. */
323     int solns, maxsolns;
324 };
325
326 /*
327  * The real recursive step in the solving function.
328  */
329 static void rsolve_real(struct rsolve_usage *usage, digit *grid)
330 {
331     int c = usage->c, r = usage->r, cr = usage->cr;
332     int i, j, n, sx, sy, bestm, bestr;
333     int *digits;
334
335     /*
336      * Firstly, check for completion! If there are no spaces left
337      * in the grid, we have a solution.
338      */
339     if (usage->nspaces == 0) {
340         if (!usage->solns) {
341             /*
342              * This is our first solution, so fill in the output grid.
343              */
344             memcpy(grid, usage->grid, cr * cr);
345         }
346         usage->solns++;
347         return;
348     }
349
350     /*
351      * Otherwise, there must be at least one space. Find the most
352      * constrained space, using the `r' field as a tie-breaker.
353      */
354     bestm = cr+1;                      /* so that any space will beat it */
355     bestr = 0;
356     i = sx = sy = -1;
357     for (j = 0; j < usage->nspaces; j++) {
358         int x = usage->spaces[j].x, y = usage->spaces[j].y;
359         int m;
360
361         /*
362          * Find the number of digits that could go in this space.
363          */
364         m = 0;
365         for (n = 0; n < cr; n++)
366             if (!usage->row[y*cr+n] && !usage->col[x*cr+n] &&
367                 !usage->blk[((y/c)*c+(x/r))*cr+n])
368                 m++;
369
370         if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
371             bestm = m;
372             bestr = usage->spaces[j].r;
373             sx = x;
374             sy = y;
375             i = j;
376         }
377     }
378
379     /*
380      * Swap that square into the final place in the spaces array,
381      * so that decrementing nspaces will remove it from the list.
382      */
383     if (i != usage->nspaces-1) {
384         struct rsolve_coord t;
385         t = usage->spaces[usage->nspaces-1];
386         usage->spaces[usage->nspaces-1] = usage->spaces[i];
387         usage->spaces[i] = t;
388     }
389
390     /*
391      * Now we've decided which square to start our recursion at,
392      * simply go through all possible values, shuffling them
393      * randomly first if necessary.
394      */
395     digits = snewn(bestm, int);
396     j = 0;
397     for (n = 0; n < cr; n++)
398         if (!usage->row[sy*cr+n] && !usage->col[sx*cr+n] &&
399             !usage->blk[((sy/c)*c+(sx/r))*cr+n]) {
400             digits[j++] = n+1;
401         }
402
403     if (usage->rs) {
404         /* shuffle */
405         for (i = j; i > 1; i--) {
406             int p = random_upto(usage->rs, i);
407             if (p != i-1) {
408                 int t = digits[p];
409                 digits[p] = digits[i-1];
410                 digits[i-1] = t;
411             }
412         }
413     }
414
415     /* And finally, go through the digit list and actually recurse. */
416     for (i = 0; i < j; i++) {
417         n = digits[i];
418
419         /* Update the usage structure to reflect the placing of this digit. */
420         usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
421             usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = TRUE;
422         usage->grid[sy*cr+sx] = n;
423         usage->nspaces--;
424
425         /* Call the solver recursively. */
426         rsolve_real(usage, grid);
427
428         /*
429          * If we have seen as many solutions as we need, terminate
430          * all processing immediately.
431          */
432         if (usage->solns >= usage->maxsolns)
433             break;
434
435         /* Revert the usage structure. */
436         usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
437             usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = FALSE;
438         usage->grid[sy*cr+sx] = 0;
439         usage->nspaces++;
440     }
441
442     sfree(digits);
443 }
444
445 /*
446  * Entry point to solver. You give it dimensions and a starting
447  * grid, which is simply an array of N^4 digits. In that array, 0
448  * means an empty square, and 1..N mean a clue square.
449  *
450  * Return value is the number of solutions found; searching will
451  * stop after the provided `max'. (Thus, you can pass max==1 to
452  * indicate that you only care about finding _one_ solution, or
453  * max==2 to indicate that you want to know the difference between
454  * a unique and non-unique solution.) The input parameter `grid' is
455  * also filled in with the _first_ (or only) solution found by the
456  * solver.
457  */
458 static int rsolve(int c, int r, digit *grid, random_state *rs, int max)
459 {
460     struct rsolve_usage *usage;
461     int x, y, cr = c*r;
462     int ret;
463
464     /*
465      * Create an rsolve_usage structure.
466      */
467     usage = snew(struct rsolve_usage);
468
469     usage->c = c;
470     usage->r = r;
471     usage->cr = cr;
472
473     usage->grid = snewn(cr * cr, digit);
474     memcpy(usage->grid, grid, cr * cr);
475
476     usage->row = snewn(cr * cr, unsigned char);
477     usage->col = snewn(cr * cr, unsigned char);
478     usage->blk = snewn(cr * cr, unsigned char);
479     memset(usage->row, FALSE, cr * cr);
480     memset(usage->col, FALSE, cr * cr);
481     memset(usage->blk, FALSE, cr * cr);
482
483     usage->spaces = snewn(cr * cr, struct rsolve_coord);
484     usage->nspaces = 0;
485
486     usage->solns = 0;
487     usage->maxsolns = max;
488
489     usage->rs = rs;
490
491     /*
492      * Now fill it in with data from the input grid.
493      */
494     for (y = 0; y < cr; y++) {
495         for (x = 0; x < cr; x++) {
496             int v = grid[y*cr+x];
497             if (v == 0) {
498                 usage->spaces[usage->nspaces].x = x;
499                 usage->spaces[usage->nspaces].y = y;
500                 if (rs)
501                     usage->spaces[usage->nspaces].r = random_bits(rs, 31);
502                 else
503                     usage->spaces[usage->nspaces].r = usage->nspaces;
504                 usage->nspaces++;
505             } else {
506                 usage->row[y*cr+v-1] = TRUE;
507                 usage->col[x*cr+v-1] = TRUE;
508                 usage->blk[((y/c)*c+(x/r))*cr+v-1] = TRUE;
509             }
510         }
511     }
512
513     /*
514      * Run the real recursive solving function.
515      */
516     rsolve_real(usage, grid);
517     ret = usage->solns;
518
519     /*
520      * Clean up the usage structure now we have our answer.
521      */
522     sfree(usage->spaces);
523     sfree(usage->blk);
524     sfree(usage->col);
525     sfree(usage->row);
526     sfree(usage->grid);
527     sfree(usage);
528
529     /*
530      * And return.
531      */
532     return ret;
533 }
534
535 /* ----------------------------------------------------------------------
536  * End of recursive solver code.
537  */
538
539 /* ----------------------------------------------------------------------
540  * Less capable non-recursive solver. This one is used to check
541  * solubility of a grid as we gradually remove numbers from it: by
542  * verifying a grid using this solver we can ensure it isn't _too_
543  * hard (e.g. does not actually require guessing and backtracking).
544  *
545  * It supports a variety of specific modes of reasoning. By
546  * enabling or disabling subsets of these modes we can arrange a
547  * range of difficulty levels.
548  */
549
550 /*
551  * Modes of reasoning currently supported:
552  *
553  *  - Positional elimination: a number must go in a particular
554  *    square because all the other empty squares in a given
555  *    row/col/blk are ruled out.
556  *
557  *  - Numeric elimination: a square must have a particular number
558  *    in because all the other numbers that could go in it are
559  *    ruled out.
560  *
561  *  - Intersectional analysis: given two domains which overlap
562  *    (hence one must be a block, and the other can be a row or
563  *    col), if the possible locations for a particular number in
564  *    one of the domains can be narrowed down to the overlap, then
565  *    that number can be ruled out everywhere but the overlap in
566  *    the other domain too.
567  *
568  *  - Set elimination: if there is a subset of the empty squares
569  *    within a domain such that the union of the possible numbers
570  *    in that subset has the same size as the subset itself, then
571  *    those numbers can be ruled out everywhere else in the domain.
572  *    (For example, if there are five empty squares and the
573  *    possible numbers in each are 12, 23, 13, 134 and 1345, then
574  *    the first three empty squares form such a subset: the numbers
575  *    1, 2 and 3 _must_ be in those three squares in some
576  *    permutation, and hence we can deduce none of them can be in
577  *    the fourth or fifth squares.)
578  *     + You can also see this the other way round, concentrating
579  *       on numbers rather than squares: if there is a subset of
580  *       the unplaced numbers within a domain such that the union
581  *       of all their possible positions has the same size as the
582  *       subset itself, then all other numbers can be ruled out for
583  *       those positions. However, it turns out that this is
584  *       exactly equivalent to the first formulation at all times:
585  *       there is a 1-1 correspondence between suitable subsets of
586  *       the unplaced numbers and suitable subsets of the unfilled
587  *       places, found by taking the _complement_ of the union of
588  *       the numbers' possible positions (or the spaces' possible
589  *       contents).
590  */
591
592 /*
593  * Within this solver, I'm going to transform all y-coordinates by
594  * inverting the significance of the block number and the position
595  * within the block. That is, we will start with the top row of
596  * each block in order, then the second row of each block in order,
597  * etc.
598  * 
599  * This transformation has the enormous advantage that it means
600  * every row, column _and_ block is described by an arithmetic
601  * progression of coordinates within the cubic array, so that I can
602  * use the same very simple function to do blockwise, row-wise and
603  * column-wise elimination.
604  */
605 #define YTRANS(y) (((y)%c)*r+(y)/c)
606 #define YUNTRANS(y) (((y)%r)*c+(y)/r)
607
608 struct nsolve_usage {
609     int c, r, cr;
610     /*
611      * We set up a cubic array, indexed by x, y and digit; each
612      * element of this array is TRUE or FALSE according to whether
613      * or not that digit _could_ in principle go in that position.
614      *
615      * The way to index this array is cube[(x*cr+y)*cr+n-1].
616      * y-coordinates in here are transformed.
617      */
618     unsigned char *cube;
619     /*
620      * This is the grid in which we write down our final
621      * deductions. y-coordinates in here are _not_ transformed.
622      */
623     digit *grid;
624     /*
625      * Now we keep track, at a slightly higher level, of what we
626      * have yet to work out, to prevent doing the same deduction
627      * many times.
628      */
629     /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
630     unsigned char *row;
631     /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
632     unsigned char *col;
633     /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
634     unsigned char *blk;
635 };
636 #define cubepos(x,y,n) (((x)*usage->cr+(y))*usage->cr+(n)-1)
637 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
638
639 /*
640  * Function called when we are certain that a particular square has
641  * a particular number in it. The y-coordinate passed in here is
642  * transformed.
643  */
644 static void nsolve_place(struct nsolve_usage *usage, int x, int y, int n)
645 {
646     int c = usage->c, r = usage->r, cr = usage->cr;
647     int i, j, bx, by;
648
649     assert(cube(x,y,n));
650
651     /*
652      * Rule out all other numbers in this square.
653      */
654     for (i = 1; i <= cr; i++)
655         if (i != n)
656             cube(x,y,i) = FALSE;
657
658     /*
659      * Rule out this number in all other positions in the row.
660      */
661     for (i = 0; i < cr; i++)
662         if (i != y)
663             cube(x,i,n) = FALSE;
664
665     /*
666      * Rule out this number in all other positions in the column.
667      */
668     for (i = 0; i < cr; i++)
669         if (i != x)
670             cube(i,y,n) = FALSE;
671
672     /*
673      * Rule out this number in all other positions in the block.
674      */
675     bx = (x/r)*r;
676     by = y % r;
677     for (i = 0; i < r; i++)
678         for (j = 0; j < c; j++)
679             if (bx+i != x || by+j*r != y)
680                 cube(bx+i,by+j*r,n) = FALSE;
681
682     /*
683      * Enter the number in the result grid.
684      */
685     usage->grid[YUNTRANS(y)*cr+x] = n;
686
687     /*
688      * Cross out this number from the list of numbers left to place
689      * in its row, its column and its block.
690      */
691     usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
692         usage->blk[((y%r)*c+(x/r))*cr+n-1] = TRUE;
693 }
694
695 static int nsolve_elim(struct nsolve_usage *usage, int start, int step
696 #ifdef STANDALONE_SOLVER
697                        , char *fmt, ...
698 #endif
699                        )
700 {
701     int c = usage->c, r = usage->r, cr = c*r;
702     int fpos, m, i;
703
704     /*
705      * Count the number of set bits within this section of the
706      * cube.
707      */
708     m = 0;
709     fpos = -1;
710     for (i = 0; i < cr; i++)
711         if (usage->cube[start+i*step]) {
712             fpos = start+i*step;
713             m++;
714         }
715
716     if (m == 1) {
717         int x, y, n;
718         assert(fpos >= 0);
719
720         n = 1 + fpos % cr;
721         y = fpos / cr;
722         x = y / cr;
723         y %= cr;
724
725         if (!usage->grid[YUNTRANS(y)*cr+x]) {
726 #ifdef STANDALONE_SOLVER
727             if (solver_show_working) {
728                 va_list ap;
729                 va_start(ap, fmt);
730                 vprintf(fmt, ap);
731                 va_end(ap);
732                 printf(":\n  placing %d at (%d,%d)\n",
733                        n, 1+x, 1+YUNTRANS(y));
734             }
735 #endif
736             nsolve_place(usage, x, y, n);
737             return TRUE;
738         }
739     }
740
741     return FALSE;
742 }
743
744 static int nsolve_intersect(struct nsolve_usage *usage,
745                             int start1, int step1, int start2, int step2
746 #ifdef STANDALONE_SOLVER
747                             , char *fmt, ...
748 #endif
749                             )
750 {
751     int c = usage->c, r = usage->r, cr = c*r;
752     int ret, i;
753
754     /*
755      * Loop over the first domain and see if there's any set bit
756      * not also in the second.
757      */
758     for (i = 0; i < cr; i++) {
759         int p = start1+i*step1;
760         if (usage->cube[p] &&
761             !(p >= start2 && p < start2+cr*step2 &&
762               (p - start2) % step2 == 0))
763             return FALSE;              /* there is, so we can't deduce */
764     }
765
766     /*
767      * We have determined that all set bits in the first domain are
768      * within its overlap with the second. So loop over the second
769      * domain and remove all set bits that aren't also in that
770      * overlap; return TRUE iff we actually _did_ anything.
771      */
772     ret = FALSE;
773     for (i = 0; i < cr; i++) {
774         int p = start2+i*step2;
775         if (usage->cube[p] &&
776             !(p >= start1 && p < start1+cr*step1 && (p - start1) % step1 == 0))
777         {
778 #ifdef STANDALONE_SOLVER
779             if (solver_show_working) {
780                 int px, py, pn;
781
782                 if (!ret) {
783                     va_list ap;
784                     va_start(ap, fmt);
785                     vprintf(fmt, ap);
786                     va_end(ap);
787                     printf(":\n");
788                 }
789
790                 pn = 1 + p % cr;
791                 py = p / cr;
792                 px = py / cr;
793                 py %= cr;
794
795                 printf("  ruling out %d at (%d,%d)\n",
796                        pn, 1+px, 1+YUNTRANS(py));
797             }
798 #endif
799             ret = TRUE;                /* we did something */
800             usage->cube[p] = 0;
801         }
802     }
803
804     return ret;
805 }
806
807 static int nsolve_set(struct nsolve_usage *usage,
808                       int start, int step1, int step2
809 #ifdef STANDALONE_SOLVER
810                       , char *fmt, ...
811 #endif
812                       )
813 {
814     int c = usage->c, r = usage->r, cr = c*r;
815     int i, j, n, count;
816     unsigned char *grid = snewn(cr*cr, unsigned char);
817     unsigned char *rowidx = snewn(cr, unsigned char);
818     unsigned char *colidx = snewn(cr, unsigned char);
819     unsigned char *set = snewn(cr, unsigned char);
820
821     /*
822      * We are passed a cr-by-cr matrix of booleans. Our first job
823      * is to winnow it by finding any definite placements - i.e.
824      * any row with a solitary 1 - and discarding that row and the
825      * column containing the 1.
826      */
827     memset(rowidx, TRUE, cr);
828     memset(colidx, TRUE, cr);
829     for (i = 0; i < cr; i++) {
830         int count = 0, first = -1;
831         for (j = 0; j < cr; j++)
832             if (usage->cube[start+i*step1+j*step2])
833                 first = j, count++;
834         if (count == 0) {
835             /*
836              * This condition actually marks a completely insoluble
837              * (i.e. internally inconsistent) puzzle. We return and
838              * report no progress made.
839              */
840             return FALSE;
841         }
842         if (count == 1)
843             rowidx[i] = colidx[first] = FALSE;
844     }
845
846     /*
847      * Convert each of rowidx/colidx from a list of 0s and 1s to a
848      * list of the indices of the 1s.
849      */
850     for (i = j = 0; i < cr; i++)
851         if (rowidx[i])
852             rowidx[j++] = i;
853     n = j;
854     for (i = j = 0; i < cr; i++)
855         if (colidx[i])
856             colidx[j++] = i;
857     assert(n == j);
858
859     /*
860      * And create the smaller matrix.
861      */
862     for (i = 0; i < n; i++)
863         for (j = 0; j < n; j++)
864             grid[i*cr+j] = usage->cube[start+rowidx[i]*step1+colidx[j]*step2];
865
866     /*
867      * Having done that, we now have a matrix in which every row
868      * has at least two 1s in. Now we search to see if we can find
869      * a rectangle of zeroes (in the set-theoretic sense of
870      * `rectangle', i.e. a subset of rows crossed with a subset of
871      * columns) whose width and height add up to n.
872      */
873
874     memset(set, 0, n);
875     count = 0;
876     while (1) {
877         /*
878          * We have a candidate set. If its size is <=1 or >=n-1
879          * then we move on immediately.
880          */
881         if (count > 1 && count < n-1) {
882             /*
883              * The number of rows we need is n-count. See if we can
884              * find that many rows which each have a zero in all
885              * the positions listed in `set'.
886              */
887             int rows = 0;
888             for (i = 0; i < n; i++) {
889                 int ok = TRUE;
890                 for (j = 0; j < n; j++)
891                     if (set[j] && grid[i*cr+j]) {
892                         ok = FALSE;
893                         break;
894                     }
895                 if (ok)
896                     rows++;
897             }
898
899             /*
900              * We expect never to be able to get _more_ than
901              * n-count suitable rows: this would imply that (for
902              * example) there are four numbers which between them
903              * have at most three possible positions, and hence it
904              * indicates a faulty deduction before this point or
905              * even a bogus clue.
906              */
907             assert(rows <= n - count);
908             if (rows >= n - count) {
909                 int progress = FALSE;
910
911                 /*
912                  * We've got one! Now, for each row which _doesn't_
913                  * satisfy the criterion, eliminate all its set
914                  * bits in the positions _not_ listed in `set'.
915                  * Return TRUE (meaning progress has been made) if
916                  * we successfully eliminated anything at all.
917                  * 
918                  * This involves referring back through
919                  * rowidx/colidx in order to work out which actual
920                  * positions in the cube to meddle with.
921                  */
922                 for (i = 0; i < n; i++) {
923                     int ok = TRUE;
924                     for (j = 0; j < n; j++)
925                         if (set[j] && grid[i*cr+j]) {
926                             ok = FALSE;
927                             break;
928                         }
929                     if (!ok) {
930                         for (j = 0; j < n; j++)
931                             if (!set[j] && grid[i*cr+j]) {
932                                 int fpos = (start+rowidx[i]*step1+
933                                             colidx[j]*step2);
934 #ifdef STANDALONE_SOLVER
935                                 if (solver_show_working) {
936                                     int px, py, pn;
937                                     
938                                     if (!progress) {
939                                         va_list ap;
940                                         va_start(ap, fmt);
941                                         vprintf(fmt, ap);
942                                         va_end(ap);
943                                         printf(":\n");
944                                     }
945
946                                     pn = 1 + fpos % cr;
947                                     py = fpos / cr;
948                                     px = py / cr;
949                                     py %= cr;
950
951                                     printf("  ruling out %d at (%d,%d)\n",
952                                            pn, 1+px, 1+YUNTRANS(py));
953                                 }
954 #endif
955                                 progress = TRUE;
956                                 usage->cube[fpos] = FALSE;
957                             }
958                     }
959                 }
960
961                 if (progress) {
962                     sfree(set);
963                     sfree(colidx);
964                     sfree(rowidx);
965                     sfree(grid);
966                     return TRUE;
967                 }
968             }
969         }
970
971         /*
972          * Binary increment: change the rightmost 0 to a 1, and
973          * change all 1s to the right of it to 0s.
974          */
975         i = n;
976         while (i > 0 && set[i-1])
977             set[--i] = 0, count--;
978         if (i > 0)
979             set[--i] = 1, count++;
980         else
981             break;                     /* done */
982     }
983
984     sfree(set);
985     sfree(colidx);
986     sfree(rowidx);
987     sfree(grid);
988
989     return FALSE;
990 }
991
992 static int nsolve(int c, int r, digit *grid)
993 {
994     struct nsolve_usage *usage;
995     int cr = c*r;
996     int x, y, n;
997     int diff = DIFF_BLOCK;
998
999     /*
1000      * Set up a usage structure as a clean slate (everything
1001      * possible).
1002      */
1003     usage = snew(struct nsolve_usage);
1004     usage->c = c;
1005     usage->r = r;
1006     usage->cr = cr;
1007     usage->cube = snewn(cr*cr*cr, unsigned char);
1008     usage->grid = grid;                /* write straight back to the input */
1009     memset(usage->cube, TRUE, cr*cr*cr);
1010
1011     usage->row = snewn(cr * cr, unsigned char);
1012     usage->col = snewn(cr * cr, unsigned char);
1013     usage->blk = snewn(cr * cr, unsigned char);
1014     memset(usage->row, FALSE, cr * cr);
1015     memset(usage->col, FALSE, cr * cr);
1016     memset(usage->blk, FALSE, cr * cr);
1017
1018     /*
1019      * Place all the clue numbers we are given.
1020      */
1021     for (x = 0; x < cr; x++)
1022         for (y = 0; y < cr; y++)
1023             if (grid[y*cr+x])
1024                 nsolve_place(usage, x, YTRANS(y), grid[y*cr+x]);
1025
1026     /*
1027      * Now loop over the grid repeatedly trying all permitted modes
1028      * of reasoning. The loop terminates if we complete an
1029      * iteration without making any progress; we then return
1030      * failure or success depending on whether the grid is full or
1031      * not.
1032      */
1033     while (1) {
1034         /*
1035          * I'd like to write `continue;' inside each of the
1036          * following loops, so that the solver returns here after
1037          * making some progress. However, I can't specify that I
1038          * want to continue an outer loop rather than the innermost
1039          * one, so I'm apologetically resorting to a goto.
1040          */
1041         cont:
1042
1043         /*
1044          * Blockwise positional elimination.
1045          */
1046         for (x = 0; x < cr; x += r)
1047             for (y = 0; y < r; y++)
1048                 for (n = 1; n <= cr; n++)
1049                     if (!usage->blk[(y*c+(x/r))*cr+n-1] &&
1050                         nsolve_elim(usage, cubepos(x,y,n), r*cr
1051 #ifdef STANDALONE_SOLVER
1052                                     , "positional elimination,"
1053                                     " block (%d,%d)", 1+x/r, 1+y
1054 #endif
1055                                     )) {
1056                         diff = max(diff, DIFF_BLOCK);
1057                         goto cont;
1058                     }
1059
1060         /*
1061          * Row-wise positional elimination.
1062          */
1063         for (y = 0; y < cr; y++)
1064             for (n = 1; n <= cr; n++)
1065                 if (!usage->row[y*cr+n-1] &&
1066                     nsolve_elim(usage, cubepos(0,y,n), cr*cr
1067 #ifdef STANDALONE_SOLVER
1068                                 , "positional elimination,"
1069                                 " row %d", 1+YUNTRANS(y)
1070 #endif
1071                                 )) {
1072                     diff = max(diff, DIFF_SIMPLE);
1073                     goto cont;
1074                 }
1075         /*
1076          * Column-wise positional elimination.
1077          */
1078         for (x = 0; x < cr; x++)
1079             for (n = 1; n <= cr; n++)
1080                 if (!usage->col[x*cr+n-1] &&
1081                     nsolve_elim(usage, cubepos(x,0,n), cr
1082 #ifdef STANDALONE_SOLVER
1083                                 , "positional elimination," " column %d", 1+x
1084 #endif
1085                                 )) {
1086                     diff = max(diff, DIFF_SIMPLE);
1087                     goto cont;
1088                 }
1089
1090         /*
1091          * Numeric elimination.
1092          */
1093         for (x = 0; x < cr; x++)
1094             for (y = 0; y < cr; y++)
1095                 if (!usage->grid[YUNTRANS(y)*cr+x] &&
1096                     nsolve_elim(usage, cubepos(x,y,1), 1
1097 #ifdef STANDALONE_SOLVER
1098                                 , "numeric elimination at (%d,%d)", 1+x,
1099                                 1+YUNTRANS(y)
1100 #endif
1101                                 )) {
1102                     diff = max(diff, DIFF_SIMPLE);
1103                     goto cont;
1104                 }
1105
1106         /*
1107          * Intersectional analysis, rows vs blocks.
1108          */
1109         for (y = 0; y < cr; y++)
1110             for (x = 0; x < cr; x += r)
1111                 for (n = 1; n <= cr; n++)
1112                     if (!usage->row[y*cr+n-1] &&
1113                         !usage->blk[((y%r)*c+(x/r))*cr+n-1] &&
1114                         (nsolve_intersect(usage, cubepos(0,y,n), cr*cr,
1115                                           cubepos(x,y%r,n), r*cr
1116 #ifdef STANDALONE_SOLVER
1117                                           , "intersectional analysis,"
1118                                           " row %d vs block (%d,%d)",
1119                                           1+YUNTRANS(y), 1+x/r, 1+y%r
1120 #endif
1121                                           ) ||
1122                          nsolve_intersect(usage, cubepos(x,y%r,n), r*cr,
1123                                           cubepos(0,y,n), cr*cr
1124 #ifdef STANDALONE_SOLVER
1125                                           , "intersectional analysis,"
1126                                           " block (%d,%d) vs row %d",
1127                                           1+x/r, 1+y%r, 1+YUNTRANS(y)
1128 #endif
1129                                           ))) {
1130                         diff = max(diff, DIFF_INTERSECT);
1131                         goto cont;
1132                     }
1133
1134         /*
1135          * Intersectional analysis, columns vs blocks.
1136          */
1137         for (x = 0; x < cr; x++)
1138             for (y = 0; y < r; y++)
1139                 for (n = 1; n <= cr; n++)
1140                     if (!usage->col[x*cr+n-1] &&
1141                         !usage->blk[(y*c+(x/r))*cr+n-1] &&
1142                         (nsolve_intersect(usage, cubepos(x,0,n), cr,
1143                                           cubepos((x/r)*r,y,n), r*cr
1144 #ifdef STANDALONE_SOLVER
1145                                           , "intersectional analysis,"
1146                                           " column %d vs block (%d,%d)",
1147                                           1+x, 1+x/r, 1+y
1148 #endif
1149                                           ) ||
1150                          nsolve_intersect(usage, cubepos((x/r)*r,y,n), r*cr,
1151                                           cubepos(x,0,n), cr
1152 #ifdef STANDALONE_SOLVER
1153                                           , "intersectional analysis,"
1154                                           " block (%d,%d) vs column %d",
1155                                           1+x/r, 1+y, 1+x
1156 #endif
1157                                           ))) {
1158                         diff = max(diff, DIFF_INTERSECT);
1159                         goto cont;
1160                     }
1161
1162         /*
1163          * Blockwise set elimination.
1164          */
1165         for (x = 0; x < cr; x += r)
1166             for (y = 0; y < r; y++)
1167                 if (nsolve_set(usage, cubepos(x,y,1), r*cr, 1
1168 #ifdef STANDALONE_SOLVER
1169                                , "set elimination, block (%d,%d)", 1+x/r, 1+y
1170 #endif
1171                                )) {
1172                     diff = max(diff, DIFF_SET);
1173                     goto cont;
1174                 }
1175
1176         /*
1177          * Row-wise set elimination.
1178          */
1179         for (y = 0; y < cr; y++)
1180             if (nsolve_set(usage, cubepos(0,y,1), cr*cr, 1
1181 #ifdef STANDALONE_SOLVER
1182                            , "set elimination, row %d", 1+YUNTRANS(y)
1183 #endif
1184                            )) {
1185                 diff = max(diff, DIFF_SET);
1186                 goto cont;
1187             }
1188
1189         /*
1190          * Column-wise set elimination.
1191          */
1192         for (x = 0; x < cr; x++)
1193             if (nsolve_set(usage, cubepos(x,0,1), cr, 1
1194 #ifdef STANDALONE_SOLVER
1195                            , "set elimination, column %d", 1+x
1196 #endif
1197                            )) {
1198                 diff = max(diff, DIFF_SET);
1199                 goto cont;
1200             }
1201
1202         /*
1203          * If we reach here, we have made no deductions in this
1204          * iteration, so the algorithm terminates.
1205          */
1206         break;
1207     }
1208
1209     sfree(usage->cube);
1210     sfree(usage->row);
1211     sfree(usage->col);
1212     sfree(usage->blk);
1213     sfree(usage);
1214
1215     for (x = 0; x < cr; x++)
1216         for (y = 0; y < cr; y++)
1217             if (!grid[y*cr+x])
1218                 return DIFF_IMPOSSIBLE;
1219     return diff;
1220 }
1221
1222 /* ----------------------------------------------------------------------
1223  * End of non-recursive solver code.
1224  */
1225
1226 /*
1227  * Check whether a grid contains a valid complete puzzle.
1228  */
1229 static int check_valid(int c, int r, digit *grid)
1230 {
1231     int cr = c*r;
1232     unsigned char *used;
1233     int x, y, n;
1234
1235     used = snewn(cr, unsigned char);
1236
1237     /*
1238      * Check that each row contains precisely one of everything.
1239      */
1240     for (y = 0; y < cr; y++) {
1241         memset(used, FALSE, cr);
1242         for (x = 0; x < cr; x++)
1243             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
1244                 used[grid[y*cr+x]-1] = TRUE;
1245         for (n = 0; n < cr; n++)
1246             if (!used[n]) {
1247                 sfree(used);
1248                 return FALSE;
1249             }
1250     }
1251
1252     /*
1253      * Check that each column contains precisely one of everything.
1254      */
1255     for (x = 0; x < cr; x++) {
1256         memset(used, FALSE, cr);
1257         for (y = 0; y < cr; y++)
1258             if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
1259                 used[grid[y*cr+x]-1] = TRUE;
1260         for (n = 0; n < cr; n++)
1261             if (!used[n]) {
1262                 sfree(used);
1263                 return FALSE;
1264             }
1265     }
1266
1267     /*
1268      * Check that each block contains precisely one of everything.
1269      */
1270     for (x = 0; x < cr; x += r) {
1271         for (y = 0; y < cr; y += c) {
1272             int xx, yy;
1273             memset(used, FALSE, cr);
1274             for (xx = x; xx < x+r; xx++)
1275                 for (yy = 0; yy < y+c; yy++)
1276                     if (grid[yy*cr+xx] > 0 && grid[yy*cr+xx] <= cr)
1277                         used[grid[yy*cr+xx]-1] = TRUE;
1278             for (n = 0; n < cr; n++)
1279                 if (!used[n]) {
1280                     sfree(used);
1281                     return FALSE;
1282                 }
1283         }
1284     }
1285
1286     sfree(used);
1287     return TRUE;
1288 }
1289
1290 static void symmetry_limit(game_params *params, int *xlim, int *ylim, int s)
1291 {
1292     int c = params->c, r = params->r, cr = c*r;
1293
1294     switch (s) {
1295       case SYMM_NONE:
1296         *xlim = *ylim = cr;
1297         break;
1298       case SYMM_ROT2:
1299         *xlim = (cr+1) / 2;
1300         *ylim = cr;
1301         break;
1302       case SYMM_REF4:
1303       case SYMM_ROT4:
1304         *xlim = *ylim = (cr+1) / 2;
1305         break;
1306     }
1307 }
1308
1309 static int symmetries(game_params *params, int x, int y, int *output, int s)
1310 {
1311     int c = params->c, r = params->r, cr = c*r;
1312     int i = 0;
1313
1314     *output++ = x;
1315     *output++ = y;
1316     i++;
1317
1318     switch (s) {
1319       case SYMM_NONE:
1320         break;                         /* just x,y is all we need */
1321       case SYMM_REF4:
1322       case SYMM_ROT4:
1323         switch (s) {
1324           case SYMM_REF4:
1325             *output++ = cr - 1 - x;
1326             *output++ = y;
1327             i++;
1328
1329             *output++ = x;
1330             *output++ = cr - 1 - y;
1331             i++;
1332             break;
1333           case SYMM_ROT4:
1334             *output++ = cr - 1 - y;
1335             *output++ = x;
1336             i++;
1337
1338             *output++ = y;
1339             *output++ = cr - 1 - x;
1340             i++;
1341             break;
1342         }
1343         /* fall through */
1344       case SYMM_ROT2:
1345         *output++ = cr - 1 - x;
1346         *output++ = cr - 1 - y;
1347         i++;
1348         break;
1349     }
1350
1351     return i;
1352 }
1353
1354 struct game_aux_info {
1355     int c, r;
1356     digit *grid;
1357 };
1358
1359 static char *new_game_seed(game_params *params, random_state *rs,
1360                            game_aux_info **aux)
1361 {
1362     int c = params->c, r = params->r, cr = c*r;
1363     int area = cr*cr;
1364     digit *grid, *grid2;
1365     struct xy { int x, y; } *locs;
1366     int nlocs;
1367     int ret;
1368     char *seed;
1369     int coords[16], ncoords;
1370     int xlim, ylim;
1371     int maxdiff;
1372
1373     /*
1374      * Adjust the maximum difficulty level to be consistent with
1375      * the puzzle size: all 2x2 puzzles appear to be Trivial
1376      * (DIFF_BLOCK) so we cannot hold out for even a Basic
1377      * (DIFF_SIMPLE) one.
1378      */
1379     maxdiff = params->diff;
1380     if (c == 2 && r == 2)
1381         maxdiff = DIFF_BLOCK;
1382
1383     grid = snewn(area, digit);
1384     locs = snewn(area, struct xy);
1385     grid2 = snewn(area, digit);
1386
1387     /*
1388      * Loop until we get a grid of the required difficulty. This is
1389      * nasty, but it seems to be unpleasantly hard to generate
1390      * difficult grids otherwise.
1391      */
1392     do {
1393         /*
1394          * Start the recursive solver with an empty grid to generate a
1395          * random solved state.
1396          */
1397         memset(grid, 0, area);
1398         ret = rsolve(c, r, grid, rs, 1);
1399         assert(ret == 1);
1400         assert(check_valid(c, r, grid));
1401
1402         /*
1403          * Save the solved grid in the aux_info.
1404          */
1405         {
1406             game_aux_info *ai = snew(game_aux_info);
1407             ai->c = c;
1408             ai->r = r;
1409             ai->grid = snewn(cr * cr, digit);
1410             memcpy(ai->grid, grid, cr * cr * sizeof(digit));
1411             *aux = ai;
1412         }
1413
1414         /*
1415          * Now we have a solved grid, start removing things from it
1416          * while preserving solubility.
1417          */
1418         symmetry_limit(params, &xlim, &ylim, params->symm);
1419         while (1) {
1420             int x, y, i, j;
1421
1422             /*
1423              * Iterate over the grid and enumerate all the filled
1424              * squares we could empty.
1425              */
1426             nlocs = 0;
1427
1428             for (x = 0; x < xlim; x++)
1429                 for (y = 0; y < ylim; y++)
1430                     if (grid[y*cr+x]) {
1431                         locs[nlocs].x = x;
1432                         locs[nlocs].y = y;
1433                         nlocs++;
1434                     }
1435
1436             /*
1437              * Now shuffle that list.
1438              */
1439             for (i = nlocs; i > 1; i--) {
1440                 int p = random_upto(rs, i);
1441                 if (p != i-1) {
1442                     struct xy t = locs[p];
1443                     locs[p] = locs[i-1];
1444                     locs[i-1] = t;
1445                 }
1446             }
1447
1448             /*
1449              * Now loop over the shuffled list and, for each element,
1450              * see whether removing that element (and its reflections)
1451              * from the grid will still leave the grid soluble by
1452              * nsolve.
1453              */
1454             for (i = 0; i < nlocs; i++) {
1455                 x = locs[i].x;
1456                 y = locs[i].y;
1457
1458                 memcpy(grid2, grid, area);
1459                 ncoords = symmetries(params, x, y, coords, params->symm);
1460                 for (j = 0; j < ncoords; j++)
1461                     grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
1462
1463                 if (nsolve(c, r, grid2) <= maxdiff) {
1464                     for (j = 0; j < ncoords; j++)
1465                         grid[coords[2*j+1]*cr+coords[2*j]] = 0;
1466                     break;
1467                 }
1468             }
1469
1470             if (i == nlocs) {
1471                 /*
1472                  * There was nothing we could remove without destroying
1473                  * solvability.
1474                  */
1475                 break;
1476             }
1477         }
1478
1479         memcpy(grid2, grid, area);
1480     } while (nsolve(c, r, grid2) != maxdiff);
1481
1482     sfree(grid2);
1483     sfree(locs);
1484
1485     /*
1486      * Now we have the grid as it will be presented to the user.
1487      * Encode it in a game seed.
1488      */
1489     {
1490         char *p;
1491         int run, i;
1492
1493         seed = snewn(5 * area, char);
1494         p = seed;
1495         run = 0;
1496         for (i = 0; i <= area; i++) {
1497             int n = (i < area ? grid[i] : -1);
1498
1499             if (!n)
1500                 run++;
1501             else {
1502                 if (run) {
1503                     while (run > 0) {
1504                         int c = 'a' - 1 + run;
1505                         if (run > 26)
1506                             c = 'z';
1507                         *p++ = c;
1508                         run -= c - ('a' - 1);
1509                     }
1510                 } else {
1511                     /*
1512                      * If there's a number in the very top left or
1513                      * bottom right, there's no point putting an
1514                      * unnecessary _ before or after it.
1515                      */
1516                     if (p > seed && n > 0)
1517                         *p++ = '_';
1518                 }
1519                 if (n > 0)
1520                     p += sprintf(p, "%d", n);
1521                 run = 0;
1522             }
1523         }
1524         assert(p - seed < 5 * area);
1525         *p++ = '\0';
1526         seed = sresize(seed, p - seed, char);
1527     }
1528
1529     sfree(grid);
1530
1531     return seed;
1532 }
1533
1534 static void game_free_aux_info(game_aux_info *aux)
1535 {
1536     sfree(aux->grid);
1537     sfree(aux);
1538 }
1539
1540 static char *validate_seed(game_params *params, char *seed)
1541 {
1542     int area = params->r * params->r * params->c * params->c;
1543     int squares = 0;
1544
1545     while (*seed) {
1546         int n = *seed++;
1547         if (n >= 'a' && n <= 'z') {
1548             squares += n - 'a' + 1;
1549         } else if (n == '_') {
1550             /* do nothing */;
1551         } else if (n > '0' && n <= '9') {
1552             squares++;
1553             while (*seed >= '0' && *seed <= '9')
1554                 seed++;
1555         } else
1556             return "Invalid character in game specification";
1557     }
1558
1559     if (squares < area)
1560         return "Not enough data to fill grid";
1561
1562     if (squares > area)
1563         return "Too much data to fit in grid";
1564
1565     return NULL;
1566 }
1567
1568 static game_state *new_game(game_params *params, char *seed)
1569 {
1570     game_state *state = snew(game_state);
1571     int c = params->c, r = params->r, cr = c*r, area = cr * cr;
1572     int i;
1573
1574     state->c = params->c;
1575     state->r = params->r;
1576
1577     state->grid = snewn(area, digit);
1578     state->immutable = snewn(area, unsigned char);
1579     memset(state->immutable, FALSE, area);
1580
1581     state->completed = state->cheated = FALSE;
1582
1583     i = 0;
1584     while (*seed) {
1585         int n = *seed++;
1586         if (n >= 'a' && n <= 'z') {
1587             int run = n - 'a' + 1;
1588             assert(i + run <= area);
1589             while (run-- > 0)
1590                 state->grid[i++] = 0;
1591         } else if (n == '_') {
1592             /* do nothing */;
1593         } else if (n > '0' && n <= '9') {
1594             assert(i < area);
1595             state->immutable[i] = TRUE;
1596             state->grid[i++] = atoi(seed-1);
1597             while (*seed >= '0' && *seed <= '9')
1598                 seed++;
1599         } else {
1600             assert(!"We can't get here");
1601         }
1602     }
1603     assert(i == area);
1604
1605     return state;
1606 }
1607
1608 static game_state *dup_game(game_state *state)
1609 {
1610     game_state *ret = snew(game_state);
1611     int c = state->c, r = state->r, cr = c*r, area = cr * cr;
1612
1613     ret->c = state->c;
1614     ret->r = state->r;
1615
1616     ret->grid = snewn(area, digit);
1617     memcpy(ret->grid, state->grid, area);
1618
1619     ret->immutable = snewn(area, unsigned char);
1620     memcpy(ret->immutable, state->immutable, area);
1621
1622     ret->completed = state->completed;
1623     ret->cheated = state->cheated;
1624
1625     return ret;
1626 }
1627
1628 static void free_game(game_state *state)
1629 {
1630     sfree(state->immutable);
1631     sfree(state->grid);
1632     sfree(state);
1633 }
1634
1635 static game_state *solve_game(game_state *state, game_aux_info *ai,
1636                               char **error)
1637 {
1638     game_state *ret;
1639     int c = state->c, r = state->r, cr = c*r;
1640     int rsolve_ret;
1641
1642     ret = dup_game(state);
1643     ret->completed = ret->cheated = TRUE;
1644
1645     /*
1646      * If we already have the solution in the aux_info, save
1647      * ourselves some time.
1648      */
1649     if (ai) {
1650
1651         assert(c == ai->c);
1652         assert(r == ai->r);
1653         memcpy(ret->grid, ai->grid, cr * cr * sizeof(digit));
1654
1655     } else {
1656         rsolve_ret = rsolve(c, r, ret->grid, NULL, 2);
1657
1658         if (rsolve_ret != 1) {
1659             free_game(ret);
1660             if (rsolve_ret == 0)
1661                 *error = "No solution exists for this puzzle";
1662             else
1663                 *error = "Multiple solutions exist for this puzzle";
1664             return NULL;
1665         }
1666     }
1667
1668     return ret;
1669 }
1670
1671 static char *grid_text_format(int c, int r, digit *grid)
1672 {
1673     int cr = c*r;
1674     int x, y;
1675     int maxlen;
1676     char *ret, *p;
1677
1678     /*
1679      * There are cr lines of digits, plus r-1 lines of block
1680      * separators. Each line contains cr digits, cr-1 separating
1681      * spaces, and c-1 two-character block separators. Thus, the
1682      * total length of a line is 2*cr+2*c-3 (not counting the
1683      * newline), and there are cr+r-1 of them.
1684      */
1685     maxlen = (cr+r-1) * (2*cr+2*c-2);
1686     ret = snewn(maxlen+1, char);
1687     p = ret;
1688
1689     for (y = 0; y < cr; y++) {
1690         for (x = 0; x < cr; x++) {
1691             int ch = grid[y * cr + x];
1692             if (ch == 0)
1693                 ch = ' ';
1694             else if (ch <= 9)
1695                 ch = '0' + ch;
1696             else
1697                 ch = 'a' + ch-10;
1698             *p++ = ch;
1699             if (x+1 < cr) {
1700                 *p++ = ' ';
1701                 if ((x+1) % r == 0) {
1702                     *p++ = '|';
1703                     *p++ = ' ';
1704                 }
1705             }
1706         }
1707         *p++ = '\n';
1708         if (y+1 < cr && (y+1) % c == 0) {
1709             for (x = 0; x < cr; x++) {
1710                 *p++ = '-';
1711                 if (x+1 < cr) {
1712                     *p++ = '-';
1713                     if ((x+1) % r == 0) {
1714                         *p++ = '+';
1715                         *p++ = '-';
1716                     }
1717                 }
1718             }
1719             *p++ = '\n';
1720         }
1721     }
1722
1723     assert(p - ret == maxlen);
1724     *p = '\0';
1725     return ret;
1726 }
1727
1728 static char *game_text_format(game_state *state)
1729 {
1730     return grid_text_format(state->c, state->r, state->grid);
1731 }
1732
1733 struct game_ui {
1734     /*
1735      * These are the coordinates of the currently highlighted
1736      * square on the grid, or -1,-1 if there isn't one. When there
1737      * is, pressing a valid number or letter key or Space will
1738      * enter that number or letter in the grid.
1739      */
1740     int hx, hy;
1741 };
1742
1743 static game_ui *new_ui(game_state *state)
1744 {
1745     game_ui *ui = snew(game_ui);
1746
1747     ui->hx = ui->hy = -1;
1748
1749     return ui;
1750 }
1751
1752 static void free_ui(game_ui *ui)
1753 {
1754     sfree(ui);
1755 }
1756
1757 static game_state *make_move(game_state *from, game_ui *ui, int x, int y,
1758                              int button)
1759 {
1760     int c = from->c, r = from->r, cr = c*r;
1761     int tx, ty;
1762     game_state *ret;
1763
1764     tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1765     ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1766
1767     if (tx >= 0 && tx < cr && ty >= 0 && ty < cr && button == LEFT_BUTTON) {
1768         if (tx == ui->hx && ty == ui->hy) {
1769             ui->hx = ui->hy = -1;
1770         } else {
1771             ui->hx = tx;
1772             ui->hy = ty;
1773         }
1774         return from;                   /* UI activity occurred */
1775     }
1776
1777     if (ui->hx != -1 && ui->hy != -1 &&
1778         ((button >= '1' && button <= '9' && button - '0' <= cr) ||
1779          (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
1780          (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
1781          button == ' ')) {
1782         int n = button - '0';
1783         if (button >= 'A' && button <= 'Z')
1784             n = button - 'A' + 10;
1785         if (button >= 'a' && button <= 'z')
1786             n = button - 'a' + 10;
1787         if (button == ' ')
1788             n = 0;
1789
1790         if (from->immutable[ui->hy*cr+ui->hx])
1791             return NULL;               /* can't overwrite this square */
1792
1793         ret = dup_game(from);
1794         ret->grid[ui->hy*cr+ui->hx] = n;
1795         ui->hx = ui->hy = -1;
1796
1797         /*
1798          * We've made a real change to the grid. Check to see
1799          * if the game has been completed.
1800          */
1801         if (!ret->completed && check_valid(c, r, ret->grid)) {
1802             ret->completed = TRUE;
1803         }
1804
1805         return ret;                    /* made a valid move */
1806     }
1807
1808     return NULL;
1809 }
1810
1811 /* ----------------------------------------------------------------------
1812  * Drawing routines.
1813  */
1814
1815 struct game_drawstate {
1816     int started;
1817     int c, r, cr;
1818     digit *grid;
1819     unsigned char *hl;
1820 };
1821
1822 #define XSIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
1823 #define YSIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
1824
1825 static void game_size(game_params *params, int *x, int *y)
1826 {
1827     int c = params->c, r = params->r, cr = c*r;
1828
1829     *x = XSIZE(cr);
1830     *y = YSIZE(cr);
1831 }
1832
1833 static float *game_colours(frontend *fe, game_state *state, int *ncolours)
1834 {
1835     float *ret = snewn(3 * NCOLOURS, float);
1836
1837     frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1838
1839     ret[COL_GRID * 3 + 0] = 0.0F;
1840     ret[COL_GRID * 3 + 1] = 0.0F;
1841     ret[COL_GRID * 3 + 2] = 0.0F;
1842
1843     ret[COL_CLUE * 3 + 0] = 0.0F;
1844     ret[COL_CLUE * 3 + 1] = 0.0F;
1845     ret[COL_CLUE * 3 + 2] = 0.0F;
1846
1847     ret[COL_USER * 3 + 0] = 0.0F;
1848     ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
1849     ret[COL_USER * 3 + 2] = 0.0F;
1850
1851     ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
1852     ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
1853     ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
1854
1855     *ncolours = NCOLOURS;
1856     return ret;
1857 }
1858
1859 static game_drawstate *game_new_drawstate(game_state *state)
1860 {
1861     struct game_drawstate *ds = snew(struct game_drawstate);
1862     int c = state->c, r = state->r, cr = c*r;
1863
1864     ds->started = FALSE;
1865     ds->c = c;
1866     ds->r = r;
1867     ds->cr = cr;
1868     ds->grid = snewn(cr*cr, digit);
1869     memset(ds->grid, 0, cr*cr);
1870     ds->hl = snewn(cr*cr, unsigned char);
1871     memset(ds->hl, 0, cr*cr);
1872
1873     return ds;
1874 }
1875
1876 static void game_free_drawstate(game_drawstate *ds)
1877 {
1878     sfree(ds->hl);
1879     sfree(ds->grid);
1880     sfree(ds);
1881 }
1882
1883 static void draw_number(frontend *fe, game_drawstate *ds, game_state *state,
1884                         int x, int y, int hl)
1885 {
1886     int c = state->c, r = state->r, cr = c*r;
1887     int tx, ty;
1888     int cx, cy, cw, ch;
1889     char str[2];
1890
1891     if (ds->grid[y*cr+x] == state->grid[y*cr+x] && ds->hl[y*cr+x] == hl)
1892         return;                        /* no change required */
1893
1894     tx = BORDER + x * TILE_SIZE + 2;
1895     ty = BORDER + y * TILE_SIZE + 2;
1896
1897     cx = tx;
1898     cy = ty;
1899     cw = TILE_SIZE-3;
1900     ch = TILE_SIZE-3;
1901
1902     if (x % r)
1903         cx--, cw++;
1904     if ((x+1) % r)
1905         cw++;
1906     if (y % c)
1907         cy--, ch++;
1908     if ((y+1) % c)
1909         ch++;
1910
1911     clip(fe, cx, cy, cw, ch);
1912
1913     /* background needs erasing? */
1914     if (ds->grid[y*cr+x] || ds->hl[y*cr+x] != hl)
1915         draw_rect(fe, cx, cy, cw, ch, hl ? COL_HIGHLIGHT : COL_BACKGROUND);
1916
1917     /* new number needs drawing? */
1918     if (state->grid[y*cr+x]) {
1919         str[1] = '\0';
1920         str[0] = state->grid[y*cr+x] + '0';
1921         if (str[0] > '9')
1922             str[0] += 'a' - ('9'+1);
1923         draw_text(fe, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
1924                   FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
1925                   state->immutable[y*cr+x] ? COL_CLUE : COL_USER, str);
1926     }
1927
1928     unclip(fe);
1929
1930     draw_update(fe, cx, cy, cw, ch);
1931
1932     ds->grid[y*cr+x] = state->grid[y*cr+x];
1933     ds->hl[y*cr+x] = hl;
1934 }
1935
1936 static void game_redraw(frontend *fe, game_drawstate *ds, game_state *oldstate,
1937                         game_state *state, int dir, game_ui *ui,
1938                         float animtime, float flashtime)
1939 {
1940     int c = state->c, r = state->r, cr = c*r;
1941     int x, y;
1942
1943     if (!ds->started) {
1944         /*
1945          * The initial contents of the window are not guaranteed
1946          * and can vary with front ends. To be on the safe side,
1947          * all games should start by drawing a big
1948          * background-colour rectangle covering the whole window.
1949          */
1950         draw_rect(fe, 0, 0, XSIZE(cr), YSIZE(cr), COL_BACKGROUND);
1951
1952         /*
1953          * Draw the grid.
1954          */
1955         for (x = 0; x <= cr; x++) {
1956             int thick = (x % r ? 0 : 1);
1957             draw_rect(fe, BORDER + x*TILE_SIZE - thick, BORDER-1,
1958                       1+2*thick, cr*TILE_SIZE+3, COL_GRID);
1959         }
1960         for (y = 0; y <= cr; y++) {
1961             int thick = (y % c ? 0 : 1);
1962             draw_rect(fe, BORDER-1, BORDER + y*TILE_SIZE - thick,
1963                       cr*TILE_SIZE+3, 1+2*thick, COL_GRID);
1964         }
1965     }
1966
1967     /*
1968      * Draw any numbers which need redrawing.
1969      */
1970     for (x = 0; x < cr; x++) {
1971         for (y = 0; y < cr; y++) {
1972             draw_number(fe, ds, state, x, y,
1973                         (x == ui->hx && y == ui->hy) ||
1974                         (flashtime > 0 &&
1975                          (flashtime <= FLASH_TIME/3 ||
1976                           flashtime >= FLASH_TIME*2/3)));
1977         }
1978     }
1979
1980     /*
1981      * Update the _entire_ grid if necessary.
1982      */
1983     if (!ds->started) {
1984         draw_update(fe, 0, 0, XSIZE(cr), YSIZE(cr));
1985         ds->started = TRUE;
1986     }
1987 }
1988
1989 static float game_anim_length(game_state *oldstate, game_state *newstate,
1990                               int dir)
1991 {
1992     return 0.0F;
1993 }
1994
1995 static float game_flash_length(game_state *oldstate, game_state *newstate,
1996                                int dir)
1997 {
1998     if (!oldstate->completed && newstate->completed &&
1999         !oldstate->cheated && !newstate->cheated)
2000         return FLASH_TIME;
2001     return 0.0F;
2002 }
2003
2004 static int game_wants_statusbar(void)
2005 {
2006     return FALSE;
2007 }
2008
2009 #ifdef COMBINED
2010 #define thegame solo
2011 #endif
2012
2013 const struct game thegame = {
2014     "Solo", "games.solo",
2015     default_params,
2016     game_fetch_preset,
2017     decode_params,
2018     encode_params,
2019     free_params,
2020     dup_params,
2021     TRUE, game_configure, custom_params,
2022     validate_params,
2023     new_game_seed,
2024     game_free_aux_info,
2025     validate_seed,
2026     new_game,
2027     dup_game,
2028     free_game,
2029     TRUE, solve_game,
2030     TRUE, game_text_format,
2031     new_ui,
2032     free_ui,
2033     make_move,
2034     game_size,
2035     game_colours,
2036     game_new_drawstate,
2037     game_free_drawstate,
2038     game_redraw,
2039     game_anim_length,
2040     game_flash_length,
2041     game_wants_statusbar,
2042 };
2043
2044 #ifdef STANDALONE_SOLVER
2045
2046 /*
2047  * gcc -DSTANDALONE_SOLVER -o solosolver solo.c malloc.c
2048  */
2049
2050 void frontend_default_colour(frontend *fe, float *output) {}
2051 void draw_text(frontend *fe, int x, int y, int fonttype, int fontsize,
2052                int align, int colour, char *text) {}
2053 void draw_rect(frontend *fe, int x, int y, int w, int h, int colour) {}
2054 void draw_line(frontend *fe, int x1, int y1, int x2, int y2, int colour) {}
2055 void draw_polygon(frontend *fe, int *coords, int npoints,
2056                   int fill, int colour) {}
2057 void clip(frontend *fe, int x, int y, int w, int h) {}
2058 void unclip(frontend *fe) {}
2059 void start_draw(frontend *fe) {}
2060 void draw_update(frontend *fe, int x, int y, int w, int h) {}
2061 void end_draw(frontend *fe) {}
2062 unsigned long random_bits(random_state *state, int bits)
2063 { assert(!"Shouldn't get randomness"); return 0; }
2064 unsigned long random_upto(random_state *state, unsigned long limit)
2065 { assert(!"Shouldn't get randomness"); return 0; }
2066
2067 void fatal(char *fmt, ...)
2068 {
2069     va_list ap;
2070
2071     fprintf(stderr, "fatal error: ");
2072
2073     va_start(ap, fmt);
2074     vfprintf(stderr, fmt, ap);
2075     va_end(ap);
2076
2077     fprintf(stderr, "\n");
2078     exit(1);
2079 }
2080
2081 int main(int argc, char **argv)
2082 {
2083     game_params *p;
2084     game_state *s;
2085     int recurse = TRUE;
2086     char *id = NULL, *seed, *err;
2087     int y, x;
2088     int grade = FALSE;
2089
2090     while (--argc > 0) {
2091         char *p = *++argv;
2092         if (!strcmp(p, "-r")) {
2093             recurse = TRUE;
2094         } else if (!strcmp(p, "-n")) {
2095             recurse = FALSE;
2096         } else if (!strcmp(p, "-v")) {
2097             solver_show_working = TRUE;
2098             recurse = FALSE;
2099         } else if (!strcmp(p, "-g")) {
2100             grade = TRUE;
2101             recurse = FALSE;
2102         } else if (*p == '-') {
2103             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0]);
2104             return 1;
2105         } else {
2106             id = p;
2107         }
2108     }
2109
2110     if (!id) {
2111         fprintf(stderr, "usage: %s [-n | -r | -g | -v] <game_id>\n", argv[0]);
2112         return 1;
2113     }
2114
2115     seed = strchr(id, ':');
2116     if (!seed) {
2117         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2118         return 1;
2119     }
2120     *seed++ = '\0';
2121
2122     p = decode_params(id);
2123     err = validate_seed(p, seed);
2124     if (err) {
2125         fprintf(stderr, "%s: %s\n", argv[0], err);
2126         return 1;
2127     }
2128     s = new_game(p, seed);
2129
2130     if (recurse) {
2131         int ret = rsolve(p->c, p->r, s->grid, NULL, 2);
2132         if (ret > 1) {
2133             fprintf(stderr, "%s: rsolve: multiple solutions detected\n",
2134                     argv[0]);
2135         }
2136     } else {
2137         int ret = nsolve(p->c, p->r, s->grid);
2138         if (grade) {
2139             if (ret == DIFF_IMPOSSIBLE) {
2140                 /*
2141                  * Now resort to rsolve to determine whether it's
2142                  * really soluble.
2143                  */
2144                 ret = rsolve(p->c, p->r, s->grid, NULL, 2);
2145                 if (ret == 0)
2146                     ret = DIFF_IMPOSSIBLE;
2147                 else if (ret == 1)
2148                     ret = DIFF_RECURSIVE;
2149                 else
2150                     ret = DIFF_AMBIGUOUS;
2151             }
2152             printf("Difficulty rating: %s\n",
2153                    ret==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
2154                    ret==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
2155                    ret==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
2156                    ret==DIFF_SET ? "Advanced (set elimination required)":
2157                    ret==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
2158                    ret==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
2159                    ret==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
2160                    "INTERNAL ERROR: unrecognised difficulty code");
2161         }
2162     }
2163
2164     printf("%s\n", grid_text_format(p->c, p->r, s->grid));
2165
2166     return 0;
2167 }
2168
2169 #endif