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