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