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