2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
6 * - reports from users are that `Trivial'-mode puzzles are still
7 * rather hard compared to newspapers' easy ones, so some better
8 * low-end difficulty grading would be nice
9 * + it's possible that really easy puzzles always have
10 * _several_ things you can do, so don't make you hunt too
11 * hard for the one deduction you can currently make
12 * + it's also possible that easy puzzles require fewer
13 * cross-eliminations: perhaps there's a higher incidence of
14 * things you can deduce by looking only at (say) rows,
15 * rather than things you have to check both rows and columns
17 * + but really, what I need to do is find some really easy
18 * puzzles and _play_ them, to see what's actually easy about
20 * + while I'm revamping this area, filling in the _last_
21 * number in a nearly-full row or column should certainly be
22 * permitted even at the lowest difficulty level.
23 * + also Owen noticed that `Basic' grids requiring numeric
24 * elimination are actually very hard, so I wonder if a
25 * difficulty gradation between that and positional-
26 * elimination-only might be in order
27 * + but it's not good to have _too_ many difficulty levels, or
28 * it'll take too long to randomly generate a given level.
30 * - it might still be nice to do some prioritisation on the
31 * removal of numbers from the grid
32 * + one possibility is to try to minimise the maximum number
33 * of filled squares in any block, which in particular ought
34 * to enforce never leaving a completely filled block in the
35 * puzzle as presented.
37 * - alternative interface modes
38 * + sudoku.com's Windows program has a palette of possible
39 * entries; you select a palette entry first and then click
40 * on the square you want it to go in, thus enabling
41 * mouse-only play. Useful for PDAs! I don't think it's
42 * actually incompatible with the current highlight-then-type
43 * approach: you _either_ highlight a palette entry and then
44 * click, _or_ you highlight a square and then type. At most
45 * one thing is ever highlighted at a time, so there's no way
47 * + then again, I don't actually like sudoku.com's interface;
48 * it's too much like a paint package whereas I prefer to
49 * think of Solo as a text editor.
50 * + another PDA-friendly possibility is a drag interface:
51 * _drag_ numbers from the palette into the grid squares.
52 * Thought experiments suggest I'd prefer that to the
53 * sudoku.com approach, but I haven't actually tried it.
57 * Solo puzzles need to be square overall (since each row and each
58 * column must contain one of every digit), but they need not be
59 * subdivided the same way internally. I am going to adopt a
60 * convention whereby I _always_ refer to `r' as the number of rows
61 * of _big_ divisions, and `c' as the number of columns of _big_
62 * divisions. Thus, a 2c by 3r puzzle looks something like this:
66 * ------+------ (Of course, you can't subdivide it the other way
67 * 1 4 5 | 6 3 2 or you'll get clashes; observe that the 4 in the
68 * 3 2 6 | 4 1 5 top left would conflict with the 4 in the second
69 * ------+------ box down on the left-hand side.)
73 * The need for a strong naming convention should now be clear:
74 * each small box is two rows of digits by three columns, while the
75 * overall puzzle has three rows of small boxes by two columns. So
76 * I will (hopefully) consistently use `r' to denote the number of
77 * rows _of small boxes_ (here 3), which is also the number of
78 * columns of digits in each small box; and `c' vice versa (here
81 * I'm also going to choose arbitrarily to list c first wherever
82 * possible: the above is a 2x3 puzzle, not a 3x2 one.
92 #ifdef STANDALONE_SOLVER
94 int solver_show_working, solver_recurse_depth;
100 * To save space, I store digits internally as unsigned char. This
101 * imposes a hard limit of 255 on the order of the puzzle. Since
102 * even a 5x5 takes unacceptably long to generate, I don't see this
103 * as a serious limitation unless something _really_ impressive
104 * happens in computing technology; but here's a typedef anyway for
105 * general good practice.
107 typedef unsigned char digit;
108 #define ORDER_MAX 255
110 #define PREFERRED_TILE_SIZE 48
111 #define TILE_SIZE (ds->tilesize)
112 #define BORDER (TILE_SIZE / 2)
113 #define GRIDEXTRA max((TILE_SIZE / 32),1)
115 #define FLASH_TIME 0.4F
117 enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
118 SYMM_REF4D, SYMM_REF8 };
121 DIFF_SIMPLE, DIFF_INTERSECT, DIFF_SET, DIFF_EXTREME, DIFF_RECURSIVE,
122 DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
124 enum { DIFF_KSINGLE, DIFF_KMINMAX, DIFF_KSUMS, DIFF_KINTERSECT };
140 * To determine all possible ways to reach a given sum by adding two or
141 * three numbers from 1..9, each of which occurs exactly once in the sum,
142 * these arrays contain a list of bitmasks for each sum value, where if
143 * bit N is set, it means that N occurs in the sum. Each list is
144 * terminated by a zero if it is shorter than the size of the array.
149 unsigned long sum_bits2[18][MAX_2SUMS];
150 unsigned long sum_bits3[25][MAX_3SUMS];
151 unsigned long sum_bits4[31][MAX_4SUMS];
153 static int find_sum_bits(unsigned long *array, int idx, int value_left,
154 int addends_left, int min_addend,
155 unsigned long bitmask_so_far)
158 assert(addends_left >= 2);
160 for (i = min_addend; i < value_left; i++) {
161 unsigned long new_bitmask = bitmask_so_far | (1L << i);
162 assert(bitmask_so_far != new_bitmask);
164 if (addends_left == 2) {
165 int j = value_left - i;
170 array[idx++] = new_bitmask | (1L << j);
172 idx = find_sum_bits(array, idx, value_left - i,
173 addends_left - 1, i + 1,
179 static void precompute_sum_bits(void)
182 for (i = 3; i < 31; i++) {
185 j = find_sum_bits(sum_bits2[i], 0, i, 2, 1, 0);
186 assert (j <= MAX_2SUMS);
191 j = find_sum_bits(sum_bits3[i], 0, i, 3, 1, 0);
192 assert (j <= MAX_3SUMS);
196 j = find_sum_bits(sum_bits4[i], 0, i, 4, 1, 0);
197 assert (j <= MAX_4SUMS);
205 * For a square puzzle, `c' and `r' indicate the puzzle
206 * parameters as described above.
208 * A jigsaw-style puzzle is indicated by r==1, in which case c
209 * can be whatever it likes (there is no constraint on
210 * compositeness - a 7x7 jigsaw sudoku makes perfect sense).
212 int c, r, symm, diff, kdiff;
213 int xtype; /* require all digits in X-diagonals */
217 struct block_structure {
221 * For text formatting, we do need c and r here.
226 * For any square index, whichblock[i] gives its block index.
228 * For 0 <= b,i < cr, blocks[b][i] gives the index of the ith
229 * square in block b. nr_squares[b] gives the number of squares
230 * in block b (also the number of valid elements in blocks[b]).
232 * blocks_data holds the data pointed to by blocks.
234 * nr_squares may be NULL for block structures where all blocks are
237 int *whichblock, **blocks, *nr_squares, *blocks_data;
238 int nr_blocks, max_nr_squares;
240 #ifdef STANDALONE_SOLVER
242 * Textual descriptions of each block. For normal Sudoku these
243 * are of the form "(1,3)"; for jigsaw they are "starting at
244 * (5,7)". So the sensible usage in both cases is to say
245 * "elimination within block %s" with one of these strings.
247 * Only blocknames itself needs individually freeing; it's all
256 * For historical reasons, I use `cr' to denote the overall
257 * width/height of the puzzle. It was a natural notation when
258 * all puzzles were divided into blocks in a grid, but doesn't
259 * really make much sense given jigsaw puzzles. However, the
260 * obvious `n' is heavily used in the solver to describe the
261 * index of a number being placed, so `cr' will have to stay.
264 struct block_structure *blocks;
265 struct block_structure *kblocks; /* Blocks for killer puzzles. */
268 unsigned char *pencil; /* c*r*c*r elements */
269 unsigned char *immutable; /* marks which digits are clues */
270 int completed, cheated;
273 static game_params *default_params(void)
275 game_params *ret = snew(game_params);
280 ret->symm = SYMM_ROT2; /* a plausible default */
281 ret->diff = DIFF_BLOCK; /* so is this */
282 ret->kdiff = DIFF_KINTERSECT; /* so is this */
287 static void free_params(game_params *params)
292 static game_params *dup_params(const game_params *params)
294 game_params *ret = snew(game_params);
295 *ret = *params; /* structure copy */
299 static int game_fetch_preset(int i, char **name, game_params **params)
304 } const presets[] = {
305 { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK, DIFF_KMINMAX, FALSE, FALSE } },
306 { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
307 { "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK, DIFF_KMINMAX, FALSE, FALSE } },
308 { "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
309 { "3x3 Basic X", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, TRUE } },
310 { "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT, DIFF_KMINMAX, FALSE, FALSE } },
311 { "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, FALSE, FALSE } },
312 { "3x3 Advanced X", { 3, 3, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, TRUE } },
313 { "3x3 Extreme", { 3, 3, SYMM_ROT2, DIFF_EXTREME, DIFF_KMINMAX, FALSE, FALSE } },
314 { "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE, DIFF_KMINMAX, FALSE, FALSE } },
315 { "3x3 Killer", { 3, 3, SYMM_NONE, DIFF_BLOCK, DIFF_KINTERSECT, FALSE, TRUE } },
316 { "9 Jigsaw Basic", { 9, 1, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
317 { "9 Jigsaw Basic X", { 9, 1, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, TRUE } },
318 { "9 Jigsaw Advanced", { 9, 1, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, FALSE, FALSE } },
320 { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
321 { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, FALSE, FALSE } },
325 if (i < 0 || i >= lenof(presets))
328 *name = dupstr(presets[i].title);
329 *params = dup_params(&presets[i].params);
334 static void decode_params(game_params *ret, char const *string)
338 ret->c = ret->r = atoi(string);
341 while (*string && isdigit((unsigned char)*string)) string++;
342 if (*string == 'x') {
344 ret->r = atoi(string);
346 while (*string && isdigit((unsigned char)*string)) string++;
349 if (*string == 'j') {
354 } else if (*string == 'x') {
357 } else if (*string == 'k') {
360 } else if (*string == 'r' || *string == 'm' || *string == 'a') {
363 if (sc == 'm' && *string == 'd') {
370 while (*string && isdigit((unsigned char)*string)) string++;
371 if (sc == 'm' && sn == 8)
372 ret->symm = SYMM_REF8;
373 if (sc == 'm' && sn == 4)
374 ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
375 if (sc == 'm' && sn == 2)
376 ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
377 if (sc == 'r' && sn == 4)
378 ret->symm = SYMM_ROT4;
379 if (sc == 'r' && sn == 2)
380 ret->symm = SYMM_ROT2;
382 ret->symm = SYMM_NONE;
383 } else if (*string == 'd') {
385 if (*string == 't') /* trivial */
386 string++, ret->diff = DIFF_BLOCK;
387 else if (*string == 'b') /* basic */
388 string++, ret->diff = DIFF_SIMPLE;
389 else if (*string == 'i') /* intermediate */
390 string++, ret->diff = DIFF_INTERSECT;
391 else if (*string == 'a') /* advanced */
392 string++, ret->diff = DIFF_SET;
393 else if (*string == 'e') /* extreme */
394 string++, ret->diff = DIFF_EXTREME;
395 else if (*string == 'u') /* unreasonable */
396 string++, ret->diff = DIFF_RECURSIVE;
398 string++; /* eat unknown character */
402 static char *encode_params(const game_params *params, int full)
407 sprintf(str, "%dx%d", params->c, params->r);
409 sprintf(str, "%dj", params->c);
416 switch (params->symm) {
417 case SYMM_REF8: strcat(str, "m8"); break;
418 case SYMM_REF4: strcat(str, "m4"); break;
419 case SYMM_REF4D: strcat(str, "md4"); break;
420 case SYMM_REF2: strcat(str, "m2"); break;
421 case SYMM_REF2D: strcat(str, "md2"); break;
422 case SYMM_ROT4: strcat(str, "r4"); break;
423 /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
424 case SYMM_NONE: strcat(str, "a"); break;
426 switch (params->diff) {
427 /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
428 case DIFF_SIMPLE: strcat(str, "db"); break;
429 case DIFF_INTERSECT: strcat(str, "di"); break;
430 case DIFF_SET: strcat(str, "da"); break;
431 case DIFF_EXTREME: strcat(str, "de"); break;
432 case DIFF_RECURSIVE: strcat(str, "du"); break;
438 static config_item *game_configure(const game_params *params)
443 ret = snewn(8, config_item);
445 ret[0].name = "Columns of sub-blocks";
446 ret[0].type = C_STRING;
447 sprintf(buf, "%d", params->c);
448 ret[0].u.string.sval = dupstr(buf);
450 ret[1].name = "Rows of sub-blocks";
451 ret[1].type = C_STRING;
452 sprintf(buf, "%d", params->r);
453 ret[1].u.string.sval = dupstr(buf);
455 ret[2].name = "\"X\" (require every number in each main diagonal)";
456 ret[2].type = C_BOOLEAN;
457 ret[2].u.boolean.bval = params->xtype;
459 ret[3].name = "Jigsaw (irregularly shaped sub-blocks)";
460 ret[3].type = C_BOOLEAN;
461 ret[3].u.boolean.bval = (params->r == 1);
463 ret[4].name = "Killer (digit sums)";
464 ret[4].type = C_BOOLEAN;
465 ret[4].u.boolean.bval = params->killer;
467 ret[5].name = "Symmetry";
468 ret[5].type = C_CHOICES;
469 ret[5].u.choices.choicenames = ":None:2-way rotation:4-way rotation:2-way mirror:"
470 "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
472 ret[5].u.choices.selected = params->symm;
474 ret[6].name = "Difficulty";
475 ret[6].type = C_CHOICES;
476 ret[6].u.choices.choicenames = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
477 ret[6].u.choices.selected = params->diff;
485 static game_params *custom_params(const config_item *cfg)
487 game_params *ret = snew(game_params);
489 ret->c = atoi(cfg[0].u.string.sval);
490 ret->r = atoi(cfg[1].u.string.sval);
491 ret->xtype = cfg[2].u.boolean.bval;
492 if (cfg[3].u.boolean.bval) {
496 ret->killer = cfg[4].u.boolean.bval;
497 ret->symm = cfg[5].u.choices.selected;
498 ret->diff = cfg[6].u.choices.selected;
499 ret->kdiff = DIFF_KINTERSECT;
504 static const char *validate_params(const game_params *params, int full)
507 return "Both dimensions must be at least 2";
508 if (params->c > ORDER_MAX || params->r > ORDER_MAX)
509 return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
510 if ((params->c * params->r) > 31)
511 return "Unable to support more than 31 distinct symbols in a puzzle";
512 if (params->killer && params->c * params->r > 9)
513 return "Killer puzzle dimensions must be smaller than 10.";
518 * ----------------------------------------------------------------------
519 * Block structure functions.
522 static struct block_structure *alloc_block_structure(int c, int r, int area,
527 struct block_structure *b = snew(struct block_structure);
530 b->nr_blocks = nr_blocks;
531 b->max_nr_squares = max_nr_squares;
532 b->c = c; b->r = r; b->area = area;
533 b->whichblock = snewn(area, int);
534 b->blocks_data = snewn(nr_blocks * max_nr_squares, int);
535 b->blocks = snewn(nr_blocks, int *);
536 b->nr_squares = snewn(nr_blocks, int);
538 for (i = 0; i < nr_blocks; i++)
539 b->blocks[i] = b->blocks_data + i*max_nr_squares;
541 #ifdef STANDALONE_SOLVER
542 b->blocknames = (char **)smalloc(c*r*(sizeof(char *)+80));
543 for (i = 0; i < c * r; i++)
544 b->blocknames[i] = NULL;
549 static void free_block_structure(struct block_structure *b)
551 if (--b->refcount == 0) {
552 sfree(b->whichblock);
554 sfree(b->blocks_data);
555 #ifdef STANDALONE_SOLVER
556 sfree(b->blocknames);
558 sfree(b->nr_squares);
563 static struct block_structure *dup_block_structure(struct block_structure *b)
565 struct block_structure *nb;
568 nb = alloc_block_structure(b->c, b->r, b->area, b->max_nr_squares,
570 memcpy(nb->nr_squares, b->nr_squares, b->nr_blocks * sizeof *b->nr_squares);
571 memcpy(nb->whichblock, b->whichblock, b->area * sizeof *b->whichblock);
572 memcpy(nb->blocks_data, b->blocks_data,
573 b->nr_blocks * b->max_nr_squares * sizeof *b->blocks_data);
574 for (i = 0; i < b->nr_blocks; i++)
575 nb->blocks[i] = nb->blocks_data + i*nb->max_nr_squares;
577 #ifdef STANDALONE_SOLVER
578 memcpy(nb->blocknames, b->blocknames, b->c * b->r *(sizeof(char *)+80));
581 for (i = 0; i < b->c * b->r; i++)
582 if (b->blocknames[i] == NULL)
583 nb->blocknames[i] = NULL;
585 nb->blocknames[i] = ((char *)nb->blocknames) + (b->blocknames[i] - (char *)b->blocknames);
591 static void split_block(struct block_structure *b, int *squares, int nr_squares)
594 int previous_block = b->whichblock[squares[0]];
595 int newblock = b->nr_blocks;
597 assert(b->max_nr_squares >= nr_squares);
598 assert(b->nr_squares[previous_block] > nr_squares);
601 b->blocks_data = sresize(b->blocks_data,
602 b->nr_blocks * b->max_nr_squares, int);
603 b->nr_squares = sresize(b->nr_squares, b->nr_blocks, int);
605 b->blocks = snewn(b->nr_blocks, int *);
606 for (i = 0; i < b->nr_blocks; i++)
607 b->blocks[i] = b->blocks_data + i*b->max_nr_squares;
608 for (i = 0; i < nr_squares; i++) {
609 assert(b->whichblock[squares[i]] == previous_block);
610 b->whichblock[squares[i]] = newblock;
611 b->blocks[newblock][i] = squares[i];
613 for (i = j = 0; i < b->nr_squares[previous_block]; i++) {
615 int sq = b->blocks[previous_block][i];
616 for (k = 0; k < nr_squares; k++)
617 if (squares[k] == sq)
620 b->blocks[previous_block][j++] = sq;
622 b->nr_squares[previous_block] -= nr_squares;
623 b->nr_squares[newblock] = nr_squares;
626 static void remove_from_block(struct block_structure *blocks, int b, int n)
629 blocks->whichblock[n] = -1;
630 for (i = j = 0; i < blocks->nr_squares[b]; i++)
631 if (blocks->blocks[b][i] != n)
632 blocks->blocks[b][j++] = blocks->blocks[b][i];
634 blocks->nr_squares[b]--;
637 /* ----------------------------------------------------------------------
640 * This solver is used for two purposes:
641 * + to check solubility of a grid as we gradually remove numbers
643 * + to solve an externally generated puzzle when the user selects
646 * It supports a variety of specific modes of reasoning. By
647 * enabling or disabling subsets of these modes we can arrange a
648 * range of difficulty levels.
652 * Modes of reasoning currently supported:
654 * - Positional elimination: a number must go in a particular
655 * square because all the other empty squares in a given
656 * row/col/blk are ruled out.
658 * - Killer minmax elimination: for killer-type puzzles, a number
659 * is impossible if choosing it would cause the sum in a killer
660 * region to be guaranteed to be too large or too small.
662 * - Numeric elimination: a square must have a particular number
663 * in because all the other numbers that could go in it are
666 * - Intersectional analysis: given two domains which overlap
667 * (hence one must be a block, and the other can be a row or
668 * col), if the possible locations for a particular number in
669 * one of the domains can be narrowed down to the overlap, then
670 * that number can be ruled out everywhere but the overlap in
671 * the other domain too.
673 * - Set elimination: if there is a subset of the empty squares
674 * within a domain such that the union of the possible numbers
675 * in that subset has the same size as the subset itself, then
676 * those numbers can be ruled out everywhere else in the domain.
677 * (For example, if there are five empty squares and the
678 * possible numbers in each are 12, 23, 13, 134 and 1345, then
679 * the first three empty squares form such a subset: the numbers
680 * 1, 2 and 3 _must_ be in those three squares in some
681 * permutation, and hence we can deduce none of them can be in
682 * the fourth or fifth squares.)
683 * + You can also see this the other way round, concentrating
684 * on numbers rather than squares: if there is a subset of
685 * the unplaced numbers within a domain such that the union
686 * of all their possible positions has the same size as the
687 * subset itself, then all other numbers can be ruled out for
688 * those positions. However, it turns out that this is
689 * exactly equivalent to the first formulation at all times:
690 * there is a 1-1 correspondence between suitable subsets of
691 * the unplaced numbers and suitable subsets of the unfilled
692 * places, found by taking the _complement_ of the union of
693 * the numbers' possible positions (or the spaces' possible
696 * - Forcing chains (see comment for solver_forcing().)
698 * - Recursion. If all else fails, we pick one of the currently
699 * most constrained empty squares and take a random guess at its
700 * contents, then continue solving on that basis and see if we
704 struct solver_usage {
706 struct block_structure *blocks, *kblocks, *extra_cages;
708 * We set up a cubic array, indexed by x, y and digit; each
709 * element of this array is TRUE or FALSE according to whether
710 * or not that digit _could_ in principle go in that position.
712 * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
713 * are macros below to help with this.
717 * This is the grid in which we write down our final
718 * deductions. y-coordinates in here are _not_ transformed.
722 * For killer-type puzzles, kclues holds the secondary clue for
723 * each cage. For derived cages, the clue is in extra_clues.
725 digit *kclues, *extra_clues;
727 * Now we keep track, at a slightly higher level, of what we
728 * have yet to work out, to prevent doing the same deduction
731 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
733 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
735 /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
737 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
738 unsigned char *diag; /* diag 0 is \, 1 is / */
744 #define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
745 #define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
746 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
747 #define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
749 #define ondiag0(xy) ((xy) % (cr+1) == 0)
750 #define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
751 #define diag0(i) ((i) * (cr+1))
752 #define diag1(i) ((i+1) * (cr-1))
755 * Function called when we are certain that a particular square has
756 * a particular number in it. The y-coordinate passed in here is
759 static void solver_place(struct solver_usage *usage, int x, int y, int n)
762 int sqindex = y*cr+x;
768 * Rule out all other numbers in this square.
770 for (i = 1; i <= cr; i++)
775 * Rule out this number in all other positions in the row.
777 for (i = 0; i < cr; i++)
782 * Rule out this number in all other positions in the column.
784 for (i = 0; i < cr; i++)
789 * Rule out this number in all other positions in the block.
791 bi = usage->blocks->whichblock[sqindex];
792 for (i = 0; i < cr; i++) {
793 int bp = usage->blocks->blocks[bi][i];
799 * Enter the number in the result grid.
801 usage->grid[sqindex] = n;
804 * Cross out this number from the list of numbers left to place
805 * in its row, its column and its block.
807 usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
808 usage->blk[bi*cr+n-1] = TRUE;
811 if (ondiag0(sqindex)) {
812 for (i = 0; i < cr; i++)
813 if (diag0(i) != sqindex)
814 cube2(diag0(i),n) = FALSE;
815 usage->diag[n-1] = TRUE;
817 if (ondiag1(sqindex)) {
818 for (i = 0; i < cr; i++)
819 if (diag1(i) != sqindex)
820 cube2(diag1(i),n) = FALSE;
821 usage->diag[cr+n-1] = TRUE;
826 #if defined STANDALONE_SOLVER && defined __GNUC__
828 * Forward-declare the functions taking printf-like format arguments
829 * with __attribute__((format)) so as to ensure the argument syntax
832 struct solver_scratch;
833 static int solver_elim(struct solver_usage *usage, int *indices,
834 const char *fmt, ...)
835 __attribute__((format(printf,3,4)));
836 static int solver_intersect(struct solver_usage *usage,
837 int *indices1, int *indices2, const char *fmt, ...)
838 __attribute__((format(printf,4,5)));
839 static int solver_set(struct solver_usage *usage,
840 struct solver_scratch *scratch,
841 int *indices, const char *fmt, ...)
842 __attribute__((format(printf,4,5)));
845 static int solver_elim(struct solver_usage *usage, int *indices
846 #ifdef STANDALONE_SOLVER
847 , const char *fmt, ...
855 * Count the number of set bits within this section of the
860 for (i = 0; i < cr; i++)
861 if (usage->cube[indices[i]]) {
875 if (!usage->grid[y*cr+x]) {
876 #ifdef STANDALONE_SOLVER
877 if (solver_show_working) {
879 printf("%*s", solver_recurse_depth*4, "");
883 printf(":\n%*s placing %d at (%d,%d)\n",
884 solver_recurse_depth*4, "", n, 1+x, 1+y);
887 solver_place(usage, x, y, n);
891 #ifdef STANDALONE_SOLVER
892 if (solver_show_working) {
894 printf("%*s", solver_recurse_depth*4, "");
898 printf(":\n%*s no possibilities available\n",
899 solver_recurse_depth*4, "");
908 static int solver_intersect(struct solver_usage *usage,
909 int *indices1, int *indices2
910 #ifdef STANDALONE_SOLVER
911 , const char *fmt, ...
919 * Loop over the first domain and see if there's any set bit
920 * not also in the second.
922 for (i = j = 0; i < cr; i++) {
924 while (j < cr && indices2[j] < p)
926 if (usage->cube[p]) {
927 if (j < cr && indices2[j] == p)
928 continue; /* both domains contain this index */
930 return 0; /* there is, so we can't deduce */
935 * We have determined that all set bits in the first domain are
936 * within its overlap with the second. So loop over the second
937 * domain and remove all set bits that aren't also in that
938 * overlap; return +1 iff we actually _did_ anything.
941 for (i = j = 0; i < cr; i++) {
943 while (j < cr && indices1[j] < p)
945 if (usage->cube[p] && (j >= cr || indices1[j] != p)) {
946 #ifdef STANDALONE_SOLVER
947 if (solver_show_working) {
952 printf("%*s", solver_recurse_depth*4, "");
964 printf("%*s ruling out %d at (%d,%d)\n",
965 solver_recurse_depth*4, "", pn, 1+px, 1+py);
968 ret = +1; /* we did something */
976 struct solver_scratch {
977 unsigned char *grid, *rowidx, *colidx, *set;
978 int *neighbours, *bfsqueue;
979 int *indexlist, *indexlist2;
980 #ifdef STANDALONE_SOLVER
985 static int solver_set(struct solver_usage *usage,
986 struct solver_scratch *scratch,
988 #ifdef STANDALONE_SOLVER
989 , const char *fmt, ...
995 unsigned char *grid = scratch->grid;
996 unsigned char *rowidx = scratch->rowidx;
997 unsigned char *colidx = scratch->colidx;
998 unsigned char *set = scratch->set;
1001 * We are passed a cr-by-cr matrix of booleans. Our first job
1002 * is to winnow it by finding any definite placements - i.e.
1003 * any row with a solitary 1 - and discarding that row and the
1004 * column containing the 1.
1006 memset(rowidx, TRUE, cr);
1007 memset(colidx, TRUE, cr);
1008 for (i = 0; i < cr; i++) {
1009 int count = 0, first = -1;
1010 for (j = 0; j < cr; j++)
1011 if (usage->cube[indices[i*cr+j]])
1015 * If count == 0, then there's a row with no 1s at all and
1016 * the puzzle is internally inconsistent. However, we ought
1017 * to have caught this already during the simpler reasoning
1018 * methods, so we can safely fail an assertion if we reach
1023 rowidx[i] = colidx[first] = FALSE;
1027 * Convert each of rowidx/colidx from a list of 0s and 1s to a
1028 * list of the indices of the 1s.
1030 for (i = j = 0; i < cr; i++)
1034 for (i = j = 0; i < cr; i++)
1040 * And create the smaller matrix.
1042 for (i = 0; i < n; i++)
1043 for (j = 0; j < n; j++)
1044 grid[i*cr+j] = usage->cube[indices[rowidx[i]*cr+colidx[j]]];
1047 * Having done that, we now have a matrix in which every row
1048 * has at least two 1s in. Now we search to see if we can find
1049 * a rectangle of zeroes (in the set-theoretic sense of
1050 * `rectangle', i.e. a subset of rows crossed with a subset of
1051 * columns) whose width and height add up to n.
1058 * We have a candidate set. If its size is <=1 or >=n-1
1059 * then we move on immediately.
1061 if (count > 1 && count < n-1) {
1063 * The number of rows we need is n-count. See if we can
1064 * find that many rows which each have a zero in all
1065 * the positions listed in `set'.
1068 for (i = 0; i < n; i++) {
1070 for (j = 0; j < n; j++)
1071 if (set[j] && grid[i*cr+j]) {
1080 * We expect never to be able to get _more_ than
1081 * n-count suitable rows: this would imply that (for
1082 * example) there are four numbers which between them
1083 * have at most three possible positions, and hence it
1084 * indicates a faulty deduction before this point or
1085 * even a bogus clue.
1087 if (rows > n - count) {
1088 #ifdef STANDALONE_SOLVER
1089 if (solver_show_working) {
1091 printf("%*s", solver_recurse_depth*4,
1096 printf(":\n%*s contradiction reached\n",
1097 solver_recurse_depth*4, "");
1103 if (rows >= n - count) {
1104 int progress = FALSE;
1107 * We've got one! Now, for each row which _doesn't_
1108 * satisfy the criterion, eliminate all its set
1109 * bits in the positions _not_ listed in `set'.
1110 * Return +1 (meaning progress has been made) if we
1111 * successfully eliminated anything at all.
1113 * This involves referring back through
1114 * rowidx/colidx in order to work out which actual
1115 * positions in the cube to meddle with.
1117 for (i = 0; i < n; i++) {
1119 for (j = 0; j < n; j++)
1120 if (set[j] && grid[i*cr+j]) {
1125 for (j = 0; j < n; j++)
1126 if (!set[j] && grid[i*cr+j]) {
1127 int fpos = indices[rowidx[i]*cr+colidx[j]];
1128 #ifdef STANDALONE_SOLVER
1129 if (solver_show_working) {
1134 printf("%*s", solver_recurse_depth*4,
1147 printf("%*s ruling out %d at (%d,%d)\n",
1148 solver_recurse_depth*4, "",
1153 usage->cube[fpos] = FALSE;
1165 * Binary increment: change the rightmost 0 to a 1, and
1166 * change all 1s to the right of it to 0s.
1169 while (i > 0 && set[i-1])
1170 set[--i] = 0, count--;
1172 set[--i] = 1, count++;
1181 * Look for forcing chains. A forcing chain is a path of
1182 * pairwise-exclusive squares (i.e. each pair of adjacent squares
1183 * in the path are in the same row, column or block) with the
1184 * following properties:
1186 * (a) Each square on the path has precisely two possible numbers.
1188 * (b) Each pair of squares which are adjacent on the path share
1189 * at least one possible number in common.
1191 * (c) Each square in the middle of the path shares _both_ of its
1192 * numbers with at least one of its neighbours (not the same
1193 * one with both neighbours).
1195 * These together imply that at least one of the possible number
1196 * choices at one end of the path forces _all_ the rest of the
1197 * numbers along the path. In order to make real use of this, we
1198 * need further properties:
1200 * (c) Ruling out some number N from the square at one end of the
1201 * path forces the square at the other end to take the same
1204 * (d) The two end squares are both in line with some third
1207 * (e) That third square currently has N as a possibility.
1209 * If we can find all of that lot, we can deduce that at least one
1210 * of the two ends of the forcing chain has number N, and that
1211 * therefore the mutually adjacent third square does not.
1213 * To find forcing chains, we're going to start a bfs at each
1214 * suitable square, once for each of its two possible numbers.
1216 static int solver_forcing(struct solver_usage *usage,
1217 struct solver_scratch *scratch)
1220 int *bfsqueue = scratch->bfsqueue;
1221 #ifdef STANDALONE_SOLVER
1222 int *bfsprev = scratch->bfsprev;
1224 unsigned char *number = scratch->grid;
1225 int *neighbours = scratch->neighbours;
1228 for (y = 0; y < cr; y++)
1229 for (x = 0; x < cr; x++) {
1233 * If this square doesn't have exactly two candidate
1234 * numbers, don't try it.
1236 * In this loop we also sum the candidate numbers,
1237 * which is a nasty hack to allow us to quickly find
1238 * `the other one' (since we will shortly know there
1241 for (count = t = 0, n = 1; n <= cr; n++)
1248 * Now attempt a bfs for each candidate.
1250 for (n = 1; n <= cr; n++)
1251 if (cube(x, y, n)) {
1252 int orign, currn, head, tail;
1259 memset(number, cr+1, cr*cr);
1261 bfsqueue[tail++] = y*cr+x;
1262 #ifdef STANDALONE_SOLVER
1263 bfsprev[y*cr+x] = -1;
1265 number[y*cr+x] = t - n;
1267 while (head < tail) {
1268 int xx, yy, nneighbours, xt, yt, i;
1270 xx = bfsqueue[head++];
1274 currn = number[yy*cr+xx];
1277 * Find neighbours of yy,xx.
1280 for (yt = 0; yt < cr; yt++)
1281 neighbours[nneighbours++] = yt*cr+xx;
1282 for (xt = 0; xt < cr; xt++)
1283 neighbours[nneighbours++] = yy*cr+xt;
1284 xt = usage->blocks->whichblock[yy*cr+xx];
1285 for (yt = 0; yt < cr; yt++)
1286 neighbours[nneighbours++] = usage->blocks->blocks[xt][yt];
1288 int sqindex = yy*cr+xx;
1289 if (ondiag0(sqindex)) {
1290 for (i = 0; i < cr; i++)
1291 neighbours[nneighbours++] = diag0(i);
1293 if (ondiag1(sqindex)) {
1294 for (i = 0; i < cr; i++)
1295 neighbours[nneighbours++] = diag1(i);
1300 * Try visiting each of those neighbours.
1302 for (i = 0; i < nneighbours; i++) {
1305 xt = neighbours[i] % cr;
1306 yt = neighbours[i] / cr;
1309 * We need this square to not be
1310 * already visited, and to include
1311 * currn as a possible number.
1313 if (number[yt*cr+xt] <= cr)
1315 if (!cube(xt, yt, currn))
1319 * Don't visit _this_ square a second
1322 if (xt == xx && yt == yy)
1326 * To continue with the bfs, we need
1327 * this square to have exactly two
1330 for (cc = tt = 0, nn = 1; nn <= cr; nn++)
1331 if (cube(xt, yt, nn))
1334 bfsqueue[tail++] = yt*cr+xt;
1335 #ifdef STANDALONE_SOLVER
1336 bfsprev[yt*cr+xt] = yy*cr+xx;
1338 number[yt*cr+xt] = tt - currn;
1342 * One other possibility is that this
1343 * might be the square in which we can
1344 * make a real deduction: if it's
1345 * adjacent to x,y, and currn is equal
1346 * to the original number we ruled out.
1348 if (currn == orign &&
1349 (xt == x || yt == y ||
1350 (usage->blocks->whichblock[yt*cr+xt] == usage->blocks->whichblock[y*cr+x]) ||
1351 (usage->diag && ((ondiag0(yt*cr+xt) && ondiag0(y*cr+x)) ||
1352 (ondiag1(yt*cr+xt) && ondiag1(y*cr+x)))))) {
1353 #ifdef STANDALONE_SOLVER
1354 if (solver_show_working) {
1355 const char *sep = "";
1357 printf("%*sforcing chain, %d at ends of ",
1358 solver_recurse_depth*4, "", orign);
1362 printf("%s(%d,%d)", sep, 1+xl,
1364 xl = bfsprev[yl*cr+xl];
1371 printf("\n%*s ruling out %d at (%d,%d)\n",
1372 solver_recurse_depth*4, "",
1376 cube(xt, yt, orign) = FALSE;
1387 static int solver_killer_minmax(struct solver_usage *usage,
1388 struct block_structure *cages, digit *clues,
1390 #ifdef STANDALONE_SOLVER
1398 int nsquares = cages->nr_squares[b];
1403 for (i = 0; i < nsquares; i++) {
1404 int n, x = cages->blocks[b][i];
1406 for (n = 1; n <= cr; n++)
1408 int maxval = 0, minval = 0;
1410 for (j = 0; j < nsquares; j++) {
1412 int y = cages->blocks[b][j];
1415 for (m = 1; m <= cr; m++)
1420 for (m = cr; m > 0; m--)
1426 if (maxval + n < clues[b]) {
1427 cube2(x, n) = FALSE;
1429 #ifdef STANDALONE_SOLVER
1430 if (solver_show_working)
1431 printf("%*s ruling out %d at (%d,%d) as too low %s\n",
1432 solver_recurse_depth*4, "killer minmax analysis",
1433 n, 1 + x%cr, 1 + x/cr, extra);
1436 if (minval + n > clues[b]) {
1437 cube2(x, n) = FALSE;
1439 #ifdef STANDALONE_SOLVER
1440 if (solver_show_working)
1441 printf("%*s ruling out %d at (%d,%d) as too high %s\n",
1442 solver_recurse_depth*4, "killer minmax analysis",
1443 n, 1 + x%cr, 1 + x/cr, extra);
1451 static int solver_killer_sums(struct solver_usage *usage, int b,
1452 struct block_structure *cages, int clue,
1454 #ifdef STANDALONE_SOLVER
1455 , const char *cage_type
1460 int i, ret, max_sums;
1461 int nsquares = cages->nr_squares[b];
1462 unsigned long *sumbits, possible_addends;
1465 assert(nsquares == 0);
1468 assert(nsquares > 0);
1470 if (nsquares < 2 || nsquares > 4)
1473 if (!cage_is_region) {
1474 int known_row = -1, known_col = -1, known_block = -1;
1476 * Verify that the cage lies entirely within one region,
1477 * so that using the precomputed sums is valid.
1479 for (i = 0; i < nsquares; i++) {
1480 int x = cages->blocks[b][i];
1482 assert(usage->grid[x] == 0);
1487 known_block = usage->blocks->whichblock[x];
1489 if (known_row != x/cr)
1491 if (known_col != x%cr)
1493 if (known_block != usage->blocks->whichblock[x])
1497 if (known_block == -1 && known_col == -1 && known_row == -1)
1500 if (nsquares == 2) {
1501 if (clue < 3 || clue > 17)
1504 sumbits = sum_bits2[clue];
1505 max_sums = MAX_2SUMS;
1506 } else if (nsquares == 3) {
1507 if (clue < 6 || clue > 24)
1510 sumbits = sum_bits3[clue];
1511 max_sums = MAX_3SUMS;
1513 if (clue < 10 || clue > 30)
1516 sumbits = sum_bits4[clue];
1517 max_sums = MAX_4SUMS;
1520 * For every possible way to get the sum, see if there is
1521 * one square in the cage that disallows all the required
1522 * addends. If we find one such square, this way to compute
1523 * the sum is impossible.
1525 possible_addends = 0;
1526 for (i = 0; i < max_sums; i++) {
1528 unsigned long bits = sumbits[i];
1533 for (j = 0; j < nsquares; j++) {
1535 unsigned long square_bits = bits;
1536 int x = cages->blocks[b][j];
1537 for (n = 1; n <= cr; n++)
1539 square_bits &= ~(1L << n);
1540 if (square_bits == 0) {
1545 possible_addends |= bits;
1548 * Now we know which addends can possibly be used to
1549 * compute the sum. Remove all other digits from the
1550 * set of possibilities.
1552 if (possible_addends == 0)
1556 for (i = 0; i < nsquares; i++) {
1558 int x = cages->blocks[b][i];
1559 for (n = 1; n <= cr; n++) {
1562 if ((possible_addends & (1 << n)) == 0) {
1563 cube2(x, n) = FALSE;
1565 #ifdef STANDALONE_SOLVER
1566 if (solver_show_working) {
1567 printf("%*s using %s\n",
1568 solver_recurse_depth*4, "killer sums analysis",
1570 printf("%*s ruling out %d at (%d,%d) due to impossible %d-sum\n",
1571 solver_recurse_depth*4, "",
1572 n, 1 + x%cr, 1 + x/cr, nsquares);
1581 static int filter_whole_cages(struct solver_usage *usage, int *squares, int n,
1587 /* First, filter squares with a clue. */
1588 for (i = j = 0; i < n; i++)
1589 if (usage->grid[squares[i]])
1590 *filtered_sum += usage->grid[squares[i]];
1592 squares[j++] = squares[i];
1596 * Filter all cages that are covered entirely by the list of
1600 for (b = 0; b < usage->kblocks->nr_blocks && off < n; b++) {
1601 int b_squares = usage->kblocks->nr_squares[b];
1608 * Find all squares of block b that lie in our list,
1609 * and make them contiguous at off, which is the current position
1610 * in the output list.
1612 for (i = 0; i < b_squares; i++) {
1613 for (j = off; j < n; j++)
1614 if (squares[j] == usage->kblocks->blocks[b][i]) {
1615 int t = squares[off + matched];
1616 squares[off + matched] = squares[j];
1622 /* If so, filter out all squares of b from the list. */
1623 if (matched != usage->kblocks->nr_squares[b]) {
1627 memmove(squares + off, squares + off + matched,
1628 (n - off - matched) * sizeof *squares);
1631 *filtered_sum += usage->kclues[b];
1637 static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
1639 struct solver_scratch *scratch = snew(struct solver_scratch);
1641 scratch->grid = snewn(cr*cr, unsigned char);
1642 scratch->rowidx = snewn(cr, unsigned char);
1643 scratch->colidx = snewn(cr, unsigned char);
1644 scratch->set = snewn(cr, unsigned char);
1645 scratch->neighbours = snewn(5*cr, int);
1646 scratch->bfsqueue = snewn(cr*cr, int);
1647 #ifdef STANDALONE_SOLVER
1648 scratch->bfsprev = snewn(cr*cr, int);
1650 scratch->indexlist = snewn(cr*cr, int); /* used for set elimination */
1651 scratch->indexlist2 = snewn(cr, int); /* only used for intersect() */
1655 static void solver_free_scratch(struct solver_scratch *scratch)
1657 #ifdef STANDALONE_SOLVER
1658 sfree(scratch->bfsprev);
1660 sfree(scratch->bfsqueue);
1661 sfree(scratch->neighbours);
1662 sfree(scratch->set);
1663 sfree(scratch->colidx);
1664 sfree(scratch->rowidx);
1665 sfree(scratch->grid);
1666 sfree(scratch->indexlist);
1667 sfree(scratch->indexlist2);
1672 * Used for passing information about difficulty levels between the solver
1676 /* Maximum levels allowed. */
1677 int maxdiff, maxkdiff;
1678 /* Levels reached by the solver. */
1682 static void solver(int cr, struct block_structure *blocks,
1683 struct block_structure *kblocks, int xtype,
1684 digit *grid, digit *kgrid, struct difficulty *dlev)
1686 struct solver_usage *usage;
1687 struct solver_scratch *scratch;
1688 int x, y, b, i, n, ret;
1689 int diff = DIFF_BLOCK;
1690 int kdiff = DIFF_KSINGLE;
1693 * Set up a usage structure as a clean slate (everything
1696 usage = snew(struct solver_usage);
1698 usage->blocks = blocks;
1700 usage->kblocks = dup_block_structure(kblocks);
1701 usage->extra_cages = alloc_block_structure (kblocks->c, kblocks->r,
1702 cr * cr, cr, cr * cr);
1703 usage->extra_clues = snewn(cr*cr, digit);
1705 usage->kblocks = usage->extra_cages = NULL;
1706 usage->extra_clues = NULL;
1708 usage->cube = snewn(cr*cr*cr, unsigned char);
1709 usage->grid = grid; /* write straight back to the input */
1714 nclues = kblocks->nr_blocks;
1716 * Allow for expansion of the killer regions, the absolute
1717 * limit is obviously one region per square.
1719 usage->kclues = snewn(cr*cr, digit);
1720 for (i = 0; i < nclues; i++) {
1721 for (n = 0; n < kblocks->nr_squares[i]; n++)
1722 if (kgrid[kblocks->blocks[i][n]] != 0)
1723 usage->kclues[i] = kgrid[kblocks->blocks[i][n]];
1724 assert(usage->kclues[i] > 0);
1726 memset(usage->kclues + nclues, 0, cr*cr - nclues);
1728 usage->kclues = NULL;
1731 memset(usage->cube, TRUE, cr*cr*cr);
1733 usage->row = snewn(cr * cr, unsigned char);
1734 usage->col = snewn(cr * cr, unsigned char);
1735 usage->blk = snewn(cr * cr, unsigned char);
1736 memset(usage->row, FALSE, cr * cr);
1737 memset(usage->col, FALSE, cr * cr);
1738 memset(usage->blk, FALSE, cr * cr);
1741 usage->diag = snewn(cr * 2, unsigned char);
1742 memset(usage->diag, FALSE, cr * 2);
1746 usage->nr_regions = cr * 3 + (xtype ? 2 : 0);
1747 usage->regions = snewn(cr * usage->nr_regions, int);
1748 usage->sq2region = snewn(cr * cr * 3, int *);
1750 for (n = 0; n < cr; n++) {
1751 for (i = 0; i < cr; i++) {
1754 b = usage->blocks->blocks[n][i];
1755 usage->regions[cr*n*3 + i] = x;
1756 usage->regions[cr*n*3 + cr + i] = y;
1757 usage->regions[cr*n*3 + 2*cr + i] = b;
1758 usage->sq2region[x*3] = usage->regions + cr*n*3;
1759 usage->sq2region[y*3 + 1] = usage->regions + cr*n*3 + cr;
1760 usage->sq2region[b*3 + 2] = usage->regions + cr*n*3 + 2*cr;
1764 scratch = solver_new_scratch(usage);
1767 * Place all the clue numbers we are given.
1769 for (x = 0; x < cr; x++)
1770 for (y = 0; y < cr; y++) {
1771 int n = grid[y*cr+x];
1774 diff = DIFF_IMPOSSIBLE;
1777 solver_place(usage, x, y, grid[y*cr+x]);
1782 * Now loop over the grid repeatedly trying all permitted modes
1783 * of reasoning. The loop terminates if we complete an
1784 * iteration without making any progress; we then return
1785 * failure or success depending on whether the grid is full or
1790 * I'd like to write `continue;' inside each of the
1791 * following loops, so that the solver returns here after
1792 * making some progress. However, I can't specify that I
1793 * want to continue an outer loop rather than the innermost
1794 * one, so I'm apologetically resorting to a goto.
1799 * Blockwise positional elimination.
1801 for (b = 0; b < cr; b++)
1802 for (n = 1; n <= cr; n++)
1803 if (!usage->blk[b*cr+n-1]) {
1804 for (i = 0; i < cr; i++)
1805 scratch->indexlist[i] = cubepos2(usage->blocks->blocks[b][i],n);
1806 ret = solver_elim(usage, scratch->indexlist
1807 #ifdef STANDALONE_SOLVER
1808 , "positional elimination,"
1809 " %d in block %s", n,
1810 usage->blocks->blocknames[b]
1814 diff = DIFF_IMPOSSIBLE;
1816 } else if (ret > 0) {
1817 diff = max(diff, DIFF_BLOCK);
1822 if (usage->kclues != NULL) {
1823 int changed = FALSE;
1826 * First, bring the kblocks into a more useful form: remove
1827 * all filled-in squares, and reduce the sum by their values.
1828 * Walk in reverse order, since otherwise remove_from_block
1829 * can move element past our loop counter.
1831 for (b = 0; b < usage->kblocks->nr_blocks; b++)
1832 for (i = usage->kblocks->nr_squares[b] -1; i >= 0; i--) {
1833 int x = usage->kblocks->blocks[b][i];
1834 int t = usage->grid[x];
1838 remove_from_block(usage->kblocks, b, x);
1839 if (t > usage->kclues[b]) {
1840 diff = DIFF_IMPOSSIBLE;
1843 usage->kclues[b] -= t;
1845 * Since cages are regions, this tells us something
1846 * about the other squares in the cage.
1848 for (n = 0; n < usage->kblocks->nr_squares[b]; n++) {
1849 cube2(usage->kblocks->blocks[b][n], t) = FALSE;
1854 * The most trivial kind of solver for killer puzzles: fill
1855 * single-square cages.
1857 for (b = 0; b < usage->kblocks->nr_blocks; b++) {
1858 int squares = usage->kblocks->nr_squares[b];
1860 int v = usage->kclues[b];
1861 if (v < 1 || v > cr) {
1862 diff = DIFF_IMPOSSIBLE;
1865 x = usage->kblocks->blocks[b][0] % cr;
1866 y = usage->kblocks->blocks[b][0] / cr;
1867 if (!cube(x, y, v)) {
1868 diff = DIFF_IMPOSSIBLE;
1871 solver_place(usage, x, y, v);
1873 #ifdef STANDALONE_SOLVER
1874 if (solver_show_working) {
1875 printf("%*s placing %d at (%d,%d)\n",
1876 solver_recurse_depth*4, "killer single-square cage",
1877 v, 1 + x%cr, 1 + x/cr);
1885 kdiff = max(kdiff, DIFF_KSINGLE);
1889 if (dlev->maxkdiff >= DIFF_KINTERSECT && usage->kclues != NULL) {
1890 int changed = FALSE;
1892 * Now, create the extra_cages information. Every full region
1893 * (row, column, or block) has the same sum total (45 for 3x3
1894 * puzzles. After we try to cover these regions with cages that
1895 * lie entirely within them, any squares that remain must bring
1896 * the total to this known value, and so they form additional
1897 * cages which aren't immediately evident in the displayed form
1900 usage->extra_cages->nr_blocks = 0;
1901 for (i = 0; i < 3; i++) {
1902 for (n = 0; n < cr; n++) {
1903 int *region = usage->regions + cr*n*3 + i*cr;
1904 int sum = cr * (cr + 1) / 2;
1907 int n_extra = usage->extra_cages->nr_blocks;
1908 int *extra_list = usage->extra_cages->blocks[n_extra];
1909 memcpy(extra_list, region, cr * sizeof *extra_list);
1911 nsquares = filter_whole_cages(usage, extra_list, nsquares, &filtered);
1913 if (nsquares == cr || nsquares == 0)
1915 if (dlev->maxdiff >= DIFF_RECURSIVE) {
1917 dlev->diff = DIFF_IMPOSSIBLE;
1923 if (nsquares == 1) {
1925 diff = DIFF_IMPOSSIBLE;
1928 x = extra_list[0] % cr;
1929 y = extra_list[0] / cr;
1930 if (!cube(x, y, sum)) {
1931 diff = DIFF_IMPOSSIBLE;
1934 solver_place(usage, x, y, sum);
1936 #ifdef STANDALONE_SOLVER
1937 if (solver_show_working) {
1938 printf("%*s placing %d at (%d,%d)\n",
1939 solver_recurse_depth*4, "killer single-square deduced cage",
1945 b = usage->kblocks->whichblock[extra_list[0]];
1946 for (x = 1; x < nsquares; x++)
1947 if (usage->kblocks->whichblock[extra_list[x]] != b)
1949 if (x == nsquares) {
1950 assert(usage->kblocks->nr_squares[b] > nsquares);
1951 split_block(usage->kblocks, extra_list, nsquares);
1952 assert(usage->kblocks->nr_squares[usage->kblocks->nr_blocks - 1] == nsquares);
1953 usage->kclues[usage->kblocks->nr_blocks - 1] = sum;
1954 usage->kclues[b] -= sum;
1956 usage->extra_cages->nr_squares[n_extra] = nsquares;
1957 usage->extra_cages->nr_blocks++;
1958 usage->extra_clues[n_extra] = sum;
1963 kdiff = max(kdiff, DIFF_KINTERSECT);
1969 * Another simple killer-type elimination. For every square in a
1970 * cage, find the minimum and maximum possible sums of all the
1971 * other squares in the same cage, and rule out possibilities
1972 * for the given square based on whether they are guaranteed to
1973 * cause the sum to be either too high or too low.
1974 * This is a special case of trying all possible sums across a
1975 * region, which is a recursive algorithm. We should probably
1976 * implement it for a higher difficulty level.
1978 if (dlev->maxkdiff >= DIFF_KMINMAX && usage->kclues != NULL) {
1979 int changed = FALSE;
1980 for (b = 0; b < usage->kblocks->nr_blocks; b++) {
1981 int ret = solver_killer_minmax(usage, usage->kblocks,
1983 #ifdef STANDALONE_SOLVER
1988 diff = DIFF_IMPOSSIBLE;
1993 for (b = 0; b < usage->extra_cages->nr_blocks; b++) {
1994 int ret = solver_killer_minmax(usage, usage->extra_cages,
1995 usage->extra_clues, b
1996 #ifdef STANDALONE_SOLVER
1997 , "using deduced cages"
2001 diff = DIFF_IMPOSSIBLE;
2007 kdiff = max(kdiff, DIFF_KMINMAX);
2013 * Try to use knowledge of which numbers can be used to generate
2015 * This can only be used if a cage lies entirely within a region.
2017 if (dlev->maxkdiff >= DIFF_KSUMS && usage->kclues != NULL) {
2018 int changed = FALSE;
2020 for (b = 0; b < usage->kblocks->nr_blocks; b++) {
2021 int ret = solver_killer_sums(usage, b, usage->kblocks,
2022 usage->kclues[b], TRUE
2023 #ifdef STANDALONE_SOLVER
2029 kdiff = max(kdiff, DIFF_KSUMS);
2030 } else if (ret < 0) {
2031 diff = DIFF_IMPOSSIBLE;
2036 for (b = 0; b < usage->extra_cages->nr_blocks; b++) {
2037 int ret = solver_killer_sums(usage, b, usage->extra_cages,
2038 usage->extra_clues[b], FALSE
2039 #ifdef STANDALONE_SOLVER
2045 kdiff = max(kdiff, DIFF_KSUMS);
2046 } else if (ret < 0) {
2047 diff = DIFF_IMPOSSIBLE;
2056 if (dlev->maxdiff <= DIFF_BLOCK)
2060 * Row-wise positional elimination.
2062 for (y = 0; y < cr; y++)
2063 for (n = 1; n <= cr; n++)
2064 if (!usage->row[y*cr+n-1]) {
2065 for (x = 0; x < cr; x++)
2066 scratch->indexlist[x] = cubepos(x, y, n);
2067 ret = solver_elim(usage, scratch->indexlist
2068 #ifdef STANDALONE_SOLVER
2069 , "positional elimination,"
2070 " %d in row %d", n, 1+y
2074 diff = DIFF_IMPOSSIBLE;
2076 } else if (ret > 0) {
2077 diff = max(diff, DIFF_SIMPLE);
2082 * Column-wise positional elimination.
2084 for (x = 0; x < cr; x++)
2085 for (n = 1; n <= cr; n++)
2086 if (!usage->col[x*cr+n-1]) {
2087 for (y = 0; y < cr; y++)
2088 scratch->indexlist[y] = cubepos(x, y, n);
2089 ret = solver_elim(usage, scratch->indexlist
2090 #ifdef STANDALONE_SOLVER
2091 , "positional elimination,"
2092 " %d in column %d", n, 1+x
2096 diff = DIFF_IMPOSSIBLE;
2098 } else if (ret > 0) {
2099 diff = max(diff, DIFF_SIMPLE);
2105 * X-diagonal positional elimination.
2108 for (n = 1; n <= cr; n++)
2109 if (!usage->diag[n-1]) {
2110 for (i = 0; i < cr; i++)
2111 scratch->indexlist[i] = cubepos2(diag0(i), n);
2112 ret = solver_elim(usage, scratch->indexlist
2113 #ifdef STANDALONE_SOLVER
2114 , "positional elimination,"
2115 " %d in \\-diagonal", n
2119 diff = DIFF_IMPOSSIBLE;
2121 } else if (ret > 0) {
2122 diff = max(diff, DIFF_SIMPLE);
2126 for (n = 1; n <= cr; n++)
2127 if (!usage->diag[cr+n-1]) {
2128 for (i = 0; i < cr; i++)
2129 scratch->indexlist[i] = cubepos2(diag1(i), n);
2130 ret = solver_elim(usage, scratch->indexlist
2131 #ifdef STANDALONE_SOLVER
2132 , "positional elimination,"
2133 " %d in /-diagonal", n
2137 diff = DIFF_IMPOSSIBLE;
2139 } else if (ret > 0) {
2140 diff = max(diff, DIFF_SIMPLE);
2147 * Numeric elimination.
2149 for (x = 0; x < cr; x++)
2150 for (y = 0; y < cr; y++)
2151 if (!usage->grid[y*cr+x]) {
2152 for (n = 1; n <= cr; n++)
2153 scratch->indexlist[n-1] = cubepos(x, y, n);
2154 ret = solver_elim(usage, scratch->indexlist
2155 #ifdef STANDALONE_SOLVER
2156 , "numeric elimination at (%d,%d)",
2161 diff = DIFF_IMPOSSIBLE;
2163 } else if (ret > 0) {
2164 diff = max(diff, DIFF_SIMPLE);
2169 if (dlev->maxdiff <= DIFF_SIMPLE)
2173 * Intersectional analysis, rows vs blocks.
2175 for (y = 0; y < cr; y++)
2176 for (b = 0; b < cr; b++)
2177 for (n = 1; n <= cr; n++) {
2178 if (usage->row[y*cr+n-1] ||
2179 usage->blk[b*cr+n-1])
2181 for (i = 0; i < cr; i++) {
2182 scratch->indexlist[i] = cubepos(i, y, n);
2183 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2186 * solver_intersect() never returns -1.
2188 if (solver_intersect(usage, scratch->indexlist,
2190 #ifdef STANDALONE_SOLVER
2191 , "intersectional analysis,"
2192 " %d in row %d vs block %s",
2193 n, 1+y, usage->blocks->blocknames[b]
2196 solver_intersect(usage, scratch->indexlist2,
2198 #ifdef STANDALONE_SOLVER
2199 , "intersectional analysis,"
2200 " %d in block %s vs row %d",
2201 n, usage->blocks->blocknames[b], 1+y
2204 diff = max(diff, DIFF_INTERSECT);
2210 * Intersectional analysis, columns vs blocks.
2212 for (x = 0; x < cr; x++)
2213 for (b = 0; b < cr; b++)
2214 for (n = 1; n <= cr; n++) {
2215 if (usage->col[x*cr+n-1] ||
2216 usage->blk[b*cr+n-1])
2218 for (i = 0; i < cr; i++) {
2219 scratch->indexlist[i] = cubepos(x, i, n);
2220 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2222 if (solver_intersect(usage, scratch->indexlist,
2224 #ifdef STANDALONE_SOLVER
2225 , "intersectional analysis,"
2226 " %d in column %d vs block %s",
2227 n, 1+x, usage->blocks->blocknames[b]
2230 solver_intersect(usage, scratch->indexlist2,
2232 #ifdef STANDALONE_SOLVER
2233 , "intersectional analysis,"
2234 " %d in block %s vs column %d",
2235 n, usage->blocks->blocknames[b], 1+x
2238 diff = max(diff, DIFF_INTERSECT);
2245 * Intersectional analysis, \-diagonal vs blocks.
2247 for (b = 0; b < cr; b++)
2248 for (n = 1; n <= cr; n++) {
2249 if (usage->diag[n-1] ||
2250 usage->blk[b*cr+n-1])
2252 for (i = 0; i < cr; i++) {
2253 scratch->indexlist[i] = cubepos2(diag0(i), n);
2254 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2256 if (solver_intersect(usage, scratch->indexlist,
2258 #ifdef STANDALONE_SOLVER
2259 , "intersectional analysis,"
2260 " %d in \\-diagonal vs block %s",
2261 n, usage->blocks->blocknames[b]
2264 solver_intersect(usage, scratch->indexlist2,
2266 #ifdef STANDALONE_SOLVER
2267 , "intersectional analysis,"
2268 " %d in block %s vs \\-diagonal",
2269 n, usage->blocks->blocknames[b]
2272 diff = max(diff, DIFF_INTERSECT);
2278 * Intersectional analysis, /-diagonal vs blocks.
2280 for (b = 0; b < cr; b++)
2281 for (n = 1; n <= cr; n++) {
2282 if (usage->diag[cr+n-1] ||
2283 usage->blk[b*cr+n-1])
2285 for (i = 0; i < cr; i++) {
2286 scratch->indexlist[i] = cubepos2(diag1(i), n);
2287 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2289 if (solver_intersect(usage, scratch->indexlist,
2291 #ifdef STANDALONE_SOLVER
2292 , "intersectional analysis,"
2293 " %d in /-diagonal vs block %s",
2294 n, usage->blocks->blocknames[b]
2297 solver_intersect(usage, scratch->indexlist2,
2299 #ifdef STANDALONE_SOLVER
2300 , "intersectional analysis,"
2301 " %d in block %s vs /-diagonal",
2302 n, usage->blocks->blocknames[b]
2305 diff = max(diff, DIFF_INTERSECT);
2311 if (dlev->maxdiff <= DIFF_INTERSECT)
2315 * Blockwise set elimination.
2317 for (b = 0; b < cr; b++) {
2318 for (i = 0; i < cr; i++)
2319 for (n = 1; n <= cr; n++)
2320 scratch->indexlist[i*cr+n-1] = cubepos2(usage->blocks->blocks[b][i], n);
2321 ret = solver_set(usage, scratch, scratch->indexlist
2322 #ifdef STANDALONE_SOLVER
2323 , "set elimination, block %s",
2324 usage->blocks->blocknames[b]
2328 diff = DIFF_IMPOSSIBLE;
2330 } else if (ret > 0) {
2331 diff = max(diff, DIFF_SET);
2337 * Row-wise set elimination.
2339 for (y = 0; y < cr; y++) {
2340 for (x = 0; x < cr; x++)
2341 for (n = 1; n <= cr; n++)
2342 scratch->indexlist[x*cr+n-1] = cubepos(x, y, n);
2343 ret = solver_set(usage, scratch, scratch->indexlist
2344 #ifdef STANDALONE_SOLVER
2345 , "set elimination, row %d", 1+y
2349 diff = DIFF_IMPOSSIBLE;
2351 } else if (ret > 0) {
2352 diff = max(diff, DIFF_SET);
2358 * Column-wise set elimination.
2360 for (x = 0; x < cr; x++) {
2361 for (y = 0; y < cr; y++)
2362 for (n = 1; n <= cr; n++)
2363 scratch->indexlist[y*cr+n-1] = cubepos(x, y, n);
2364 ret = solver_set(usage, scratch, scratch->indexlist
2365 #ifdef STANDALONE_SOLVER
2366 , "set elimination, column %d", 1+x
2370 diff = DIFF_IMPOSSIBLE;
2372 } else if (ret > 0) {
2373 diff = max(diff, DIFF_SET);
2380 * \-diagonal set elimination.
2382 for (i = 0; i < cr; i++)
2383 for (n = 1; n <= cr; n++)
2384 scratch->indexlist[i*cr+n-1] = cubepos2(diag0(i), n);
2385 ret = solver_set(usage, scratch, scratch->indexlist
2386 #ifdef STANDALONE_SOLVER
2387 , "set elimination, \\-diagonal"
2391 diff = DIFF_IMPOSSIBLE;
2393 } else if (ret > 0) {
2394 diff = max(diff, DIFF_SET);
2399 * /-diagonal set elimination.
2401 for (i = 0; i < cr; i++)
2402 for (n = 1; n <= cr; n++)
2403 scratch->indexlist[i*cr+n-1] = cubepos2(diag1(i), n);
2404 ret = solver_set(usage, scratch, scratch->indexlist
2405 #ifdef STANDALONE_SOLVER
2406 , "set elimination, /-diagonal"
2410 diff = DIFF_IMPOSSIBLE;
2412 } else if (ret > 0) {
2413 diff = max(diff, DIFF_SET);
2418 if (dlev->maxdiff <= DIFF_SET)
2422 * Row-vs-column set elimination on a single number.
2424 for (n = 1; n <= cr; n++) {
2425 for (y = 0; y < cr; y++)
2426 for (x = 0; x < cr; x++)
2427 scratch->indexlist[y*cr+x] = cubepos(x, y, n);
2428 ret = solver_set(usage, scratch, scratch->indexlist
2429 #ifdef STANDALONE_SOLVER
2430 , "positional set elimination, number %d", n
2434 diff = DIFF_IMPOSSIBLE;
2436 } else if (ret > 0) {
2437 diff = max(diff, DIFF_EXTREME);
2445 if (solver_forcing(usage, scratch)) {
2446 diff = max(diff, DIFF_EXTREME);
2451 * If we reach here, we have made no deductions in this
2452 * iteration, so the algorithm terminates.
2458 * Last chance: if we haven't fully solved the puzzle yet, try
2459 * recursing based on guesses for a particular square. We pick
2460 * one of the most constrained empty squares we can find, which
2461 * has the effect of pruning the search tree as much as
2464 if (dlev->maxdiff >= DIFF_RECURSIVE) {
2465 int best, bestcount;
2470 for (y = 0; y < cr; y++)
2471 for (x = 0; x < cr; x++)
2472 if (!grid[y*cr+x]) {
2476 * An unfilled square. Count the number of
2477 * possible digits in it.
2480 for (n = 1; n <= cr; n++)
2485 * We should have found any impossibilities
2486 * already, so this can safely be an assert.
2490 if (count < bestcount) {
2498 digit *list, *ingrid, *outgrid;
2500 diff = DIFF_IMPOSSIBLE; /* no solution found yet */
2503 * Attempt recursion.
2508 list = snewn(cr, digit);
2509 ingrid = snewn(cr * cr, digit);
2510 outgrid = snewn(cr * cr, digit);
2511 memcpy(ingrid, grid, cr * cr);
2513 /* Make a list of the possible digits. */
2514 for (j = 0, n = 1; n <= cr; n++)
2518 #ifdef STANDALONE_SOLVER
2519 if (solver_show_working) {
2520 const char *sep = "";
2521 printf("%*srecursing on (%d,%d) [",
2522 solver_recurse_depth*4, "", x + 1, y + 1);
2523 for (i = 0; i < j; i++) {
2524 printf("%s%d", sep, list[i]);
2532 * And step along the list, recursing back into the
2533 * main solver at every stage.
2535 for (i = 0; i < j; i++) {
2536 memcpy(outgrid, ingrid, cr * cr);
2537 outgrid[y*cr+x] = list[i];
2539 #ifdef STANDALONE_SOLVER
2540 if (solver_show_working)
2541 printf("%*sguessing %d at (%d,%d)\n",
2542 solver_recurse_depth*4, "", list[i], x + 1, y + 1);
2543 solver_recurse_depth++;
2546 solver(cr, blocks, kblocks, xtype, outgrid, kgrid, dlev);
2548 #ifdef STANDALONE_SOLVER
2549 solver_recurse_depth--;
2550 if (solver_show_working) {
2551 printf("%*sretracting %d at (%d,%d)\n",
2552 solver_recurse_depth*4, "", list[i], x + 1, y + 1);
2557 * If we have our first solution, copy it into the
2558 * grid we will return.
2560 if (diff == DIFF_IMPOSSIBLE && dlev->diff != DIFF_IMPOSSIBLE)
2561 memcpy(grid, outgrid, cr*cr);
2563 if (dlev->diff == DIFF_AMBIGUOUS)
2564 diff = DIFF_AMBIGUOUS;
2565 else if (dlev->diff == DIFF_IMPOSSIBLE)
2566 /* do not change our return value */;
2568 /* the recursion turned up exactly one solution */
2569 if (diff == DIFF_IMPOSSIBLE)
2570 diff = DIFF_RECURSIVE;
2572 diff = DIFF_AMBIGUOUS;
2576 * As soon as we've found more than one solution,
2577 * give up immediately.
2579 if (diff == DIFF_AMBIGUOUS)
2590 * We're forbidden to use recursion, so we just see whether
2591 * our grid is fully solved, and return DIFF_IMPOSSIBLE
2594 for (y = 0; y < cr; y++)
2595 for (x = 0; x < cr; x++)
2597 diff = DIFF_IMPOSSIBLE;
2602 dlev->kdiff = kdiff;
2604 #ifdef STANDALONE_SOLVER
2605 if (solver_show_working)
2606 printf("%*s%s found\n",
2607 solver_recurse_depth*4, "",
2608 diff == DIFF_IMPOSSIBLE ? "no solution" :
2609 diff == DIFF_AMBIGUOUS ? "multiple solutions" :
2613 sfree(usage->sq2region);
2614 sfree(usage->regions);
2619 if (usage->kblocks) {
2620 free_block_structure(usage->kblocks);
2621 free_block_structure(usage->extra_cages);
2622 sfree(usage->extra_clues);
2624 if (usage->kclues) sfree(usage->kclues);
2627 solver_free_scratch(scratch);
2630 /* ----------------------------------------------------------------------
2631 * End of solver code.
2634 /* ----------------------------------------------------------------------
2635 * Killer set generator.
2638 /* ----------------------------------------------------------------------
2639 * Solo filled-grid generator.
2641 * This grid generator works by essentially trying to solve a grid
2642 * starting from no clues, and not worrying that there's more than
2643 * one possible solution. Unfortunately, it isn't computationally
2644 * feasible to do this by calling the above solver with an empty
2645 * grid, because that one needs to allocate a lot of scratch space
2646 * at every recursion level. Instead, I have a much simpler
2647 * algorithm which I shamelessly copied from a Python solver
2648 * written by Andrew Wilkinson (which is GPLed, but I've reused
2649 * only ideas and no code). It mostly just does the obvious
2650 * recursive thing: pick an empty square, put one of the possible
2651 * digits in it, recurse until all squares are filled, backtrack
2652 * and change some choices if necessary.
2654 * The clever bit is that every time it chooses which square to
2655 * fill in next, it does so by counting the number of _possible_
2656 * numbers that can go in each square, and it prioritises so that
2657 * it picks a square with the _lowest_ number of possibilities. The
2658 * idea is that filling in lots of the obvious bits (particularly
2659 * any squares with only one possibility) will cut down on the list
2660 * of possibilities for other squares and hence reduce the enormous
2661 * search space as much as possible as early as possible.
2663 * The use of bit sets implies that we support puzzles up to a size of
2664 * 32x32 (less if anyone finds a 16-bit machine to compile this on).
2668 * Internal data structure used in gridgen to keep track of
2671 struct gridgen_coord { int x, y, r; };
2672 struct gridgen_usage {
2674 struct block_structure *blocks, *kblocks;
2675 /* grid is a copy of the input grid, modified as we go along */
2678 * Bitsets. In each of them, bit n is set if digit n has been placed
2679 * in the corresponding region. row, col and blk are used for all
2680 * puzzles. cge is used only for killer puzzles, and diag is used
2681 * only for x-type puzzles.
2682 * All of these have cr entries, except diag which only has 2,
2683 * and cge, which has as many entries as kblocks.
2685 unsigned int *row, *col, *blk, *cge, *diag;
2686 /* This lists all the empty spaces remaining in the grid. */
2687 struct gridgen_coord *spaces;
2689 /* If we need randomisation in the solve, this is our random state. */
2693 static void gridgen_place(struct gridgen_usage *usage, int x, int y, digit n)
2695 unsigned int bit = 1 << n;
2697 usage->row[y] |= bit;
2698 usage->col[x] |= bit;
2699 usage->blk[usage->blocks->whichblock[y*cr+x]] |= bit;
2701 usage->cge[usage->kblocks->whichblock[y*cr+x]] |= bit;
2703 if (ondiag0(y*cr+x))
2704 usage->diag[0] |= bit;
2705 if (ondiag1(y*cr+x))
2706 usage->diag[1] |= bit;
2708 usage->grid[y*cr+x] = n;
2711 static void gridgen_remove(struct gridgen_usage *usage, int x, int y, digit n)
2713 unsigned int mask = ~(1 << n);
2715 usage->row[y] &= mask;
2716 usage->col[x] &= mask;
2717 usage->blk[usage->blocks->whichblock[y*cr+x]] &= mask;
2719 usage->cge[usage->kblocks->whichblock[y*cr+x]] &= mask;
2721 if (ondiag0(y*cr+x))
2722 usage->diag[0] &= mask;
2723 if (ondiag1(y*cr+x))
2724 usage->diag[1] &= mask;
2726 usage->grid[y*cr+x] = 0;
2732 * The real recursive step in the generating function.
2734 * Return values: 1 means solution found, 0 means no solution
2735 * found on this branch.
2737 static int gridgen_real(struct gridgen_usage *usage, digit *grid, int *steps)
2740 int i, j, n, sx, sy, bestm, bestr, ret;
2745 * Firstly, check for completion! If there are no spaces left
2746 * in the grid, we have a solution.
2748 if (usage->nspaces == 0)
2752 * Next, abandon generation if we went over our steps limit.
2759 * Otherwise, there must be at least one space. Find the most
2760 * constrained space, using the `r' field as a tie-breaker.
2762 bestm = cr+1; /* so that any space will beat it */
2766 for (j = 0; j < usage->nspaces; j++) {
2767 int x = usage->spaces[j].x, y = usage->spaces[j].y;
2768 unsigned int used_xy;
2771 m = usage->blocks->whichblock[y*cr+x];
2772 used_xy = usage->row[y] | usage->col[x] | usage->blk[m];
2773 if (usage->cge != NULL)
2774 used_xy |= usage->cge[usage->kblocks->whichblock[y*cr+x]];
2775 if (usage->cge != NULL)
2776 used_xy |= usage->cge[usage->kblocks->whichblock[y*cr+x]];
2777 if (usage->diag != NULL) {
2778 if (ondiag0(y*cr+x))
2779 used_xy |= usage->diag[0];
2780 if (ondiag1(y*cr+x))
2781 used_xy |= usage->diag[1];
2785 * Find the number of digits that could go in this space.
2788 for (n = 1; n <= cr; n++) {
2789 unsigned int bit = 1 << n;
2790 if ((used_xy & bit) == 0)
2793 if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
2795 bestr = usage->spaces[j].r;
2804 * Swap that square into the final place in the spaces array,
2805 * so that decrementing nspaces will remove it from the list.
2807 if (i != usage->nspaces-1) {
2808 struct gridgen_coord t;
2809 t = usage->spaces[usage->nspaces-1];
2810 usage->spaces[usage->nspaces-1] = usage->spaces[i];
2811 usage->spaces[i] = t;
2815 * Now we've decided which square to start our recursion at,
2816 * simply go through all possible values, shuffling them
2817 * randomly first if necessary.
2819 digits = snewn(bestm, int);
2822 for (n = 1; n <= cr; n++) {
2823 unsigned int bit = 1 << n;
2825 if ((used & bit) == 0)
2830 shuffle(digits, j, sizeof(*digits), usage->rs);
2832 /* And finally, go through the digit list and actually recurse. */
2834 for (i = 0; i < j; i++) {
2837 /* Update the usage structure to reflect the placing of this digit. */
2838 gridgen_place(usage, sx, sy, n);
2841 /* Call the solver recursively. Stop when we find a solution. */
2842 if (gridgen_real(usage, grid, steps)) {
2847 /* Revert the usage structure. */
2848 gridgen_remove(usage, sx, sy, n);
2857 * Entry point to generator. You give it parameters and a starting
2858 * grid, which is simply an array of cr*cr digits.
2860 static int gridgen(int cr, struct block_structure *blocks,
2861 struct block_structure *kblocks, int xtype,
2862 digit *grid, random_state *rs, int maxsteps)
2864 struct gridgen_usage *usage;
2868 * Clear the grid to start with.
2870 memset(grid, 0, cr*cr);
2873 * Create a gridgen_usage structure.
2875 usage = snew(struct gridgen_usage);
2878 usage->blocks = blocks;
2882 usage->row = snewn(cr, unsigned int);
2883 usage->col = snewn(cr, unsigned int);
2884 usage->blk = snewn(cr, unsigned int);
2885 if (kblocks != NULL) {
2886 usage->kblocks = kblocks;
2887 usage->cge = snewn(usage->kblocks->nr_blocks, unsigned int);
2888 memset(usage->cge, FALSE, kblocks->nr_blocks * sizeof *usage->cge);
2893 memset(usage->row, 0, cr * sizeof *usage->row);
2894 memset(usage->col, 0, cr * sizeof *usage->col);
2895 memset(usage->blk, 0, cr * sizeof *usage->blk);
2898 usage->diag = snewn(2, unsigned int);
2899 memset(usage->diag, 0, 2 * sizeof *usage->diag);
2905 * Begin by filling in the whole top row with randomly chosen
2906 * numbers. This cannot introduce any bias or restriction on
2907 * the available grids, since we already know those numbers
2908 * are all distinct so all we're doing is choosing their
2911 for (x = 0; x < cr; x++)
2913 shuffle(grid, cr, sizeof(*grid), rs);
2914 for (x = 0; x < cr; x++)
2915 gridgen_place(usage, x, 0, grid[x]);
2917 usage->spaces = snewn(cr * cr, struct gridgen_coord);
2923 * Initialise the list of grid spaces, taking care to leave
2924 * out the row I've already filled in above.
2926 for (y = 1; y < cr; y++) {
2927 for (x = 0; x < cr; x++) {
2928 usage->spaces[usage->nspaces].x = x;
2929 usage->spaces[usage->nspaces].y = y;
2930 usage->spaces[usage->nspaces].r = random_bits(rs, 31);
2936 * Run the real generator function.
2938 ret = gridgen_real(usage, grid, &maxsteps);
2941 * Clean up the usage structure now we have our answer.
2943 sfree(usage->spaces);
2953 /* ----------------------------------------------------------------------
2954 * End of grid generator code.
2957 static int check_killer_cage_sum(struct block_structure *kblocks,
2958 digit *kgrid, digit *grid, int blk)
2961 * Returns: -1 if the cage has any empty square; 0 if all squares
2962 * are full but the sum is wrong; +1 if all squares are full and
2963 * they have the right sum.
2965 * Does not check uniqueness of numbers within the cage; that's
2966 * done elsewhere (because in error highlighting it needs to be
2967 * detected separately so as to flag the error in a visually
2970 int n_squares = kblocks->nr_squares[blk];
2971 int sum = 0, clue = 0;
2974 for (i = 0; i < n_squares; i++) {
2975 int xy = kblocks->blocks[blk][i];
2992 * Check whether a grid contains a valid complete puzzle.
2994 static int check_valid(int cr, struct block_structure *blocks,
2995 struct block_structure *kblocks,
2996 digit *kgrid, int xtype, digit *grid)
2998 unsigned char *used;
3001 used = snewn(cr, unsigned char);
3004 * Check that each row contains precisely one of everything.
3006 for (y = 0; y < cr; y++) {
3007 memset(used, FALSE, cr);
3008 for (x = 0; x < cr; x++)
3009 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
3010 used[grid[y*cr+x]-1] = TRUE;
3011 for (n = 0; n < cr; n++)
3019 * Check that each column contains precisely one of everything.
3021 for (x = 0; x < cr; x++) {
3022 memset(used, FALSE, cr);
3023 for (y = 0; y < cr; y++)
3024 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
3025 used[grid[y*cr+x]-1] = TRUE;
3026 for (n = 0; n < cr; n++)
3034 * Check that each block contains precisely one of everything.
3036 for (i = 0; i < cr; i++) {
3037 memset(used, FALSE, cr);
3038 for (j = 0; j < cr; j++)
3039 if (grid[blocks->blocks[i][j]] > 0 &&
3040 grid[blocks->blocks[i][j]] <= cr)
3041 used[grid[blocks->blocks[i][j]]-1] = TRUE;
3042 for (n = 0; n < cr; n++)
3050 * Check that each Killer cage, if any, contains at most one of
3051 * everything. If we also know the clues for those cages (which we
3052 * might not, when this function is called early in puzzle
3053 * generation), we also check that they all have the right sum.
3056 for (i = 0; i < kblocks->nr_blocks; i++) {
3057 memset(used, FALSE, cr);
3058 for (j = 0; j < kblocks->nr_squares[i]; j++)
3059 if (grid[kblocks->blocks[i][j]] > 0 &&
3060 grid[kblocks->blocks[i][j]] <= cr) {
3061 if (used[grid[kblocks->blocks[i][j]]-1]) {
3065 used[grid[kblocks->blocks[i][j]]-1] = TRUE;
3068 if (kgrid && check_killer_cage_sum(kblocks, kgrid, grid, i) != 1) {
3076 * Check that each diagonal contains precisely one of everything.
3079 memset(used, FALSE, cr);
3080 for (i = 0; i < cr; i++)
3081 if (grid[diag0(i)] > 0 && grid[diag0(i)] <= cr)
3082 used[grid[diag0(i)]-1] = TRUE;
3083 for (n = 0; n < cr; n++)
3088 for (i = 0; i < cr; i++)
3089 if (grid[diag1(i)] > 0 && grid[diag1(i)] <= cr)
3090 used[grid[diag1(i)]-1] = TRUE;
3091 for (n = 0; n < cr; n++)
3102 static int symmetries(const game_params *params, int x, int y,
3105 int c = params->c, r = params->r, cr = c*r;
3108 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
3114 break; /* just x,y is all we need */
3116 ADD(cr - 1 - x, cr - 1 - y);
3121 ADD(cr - 1 - x, cr - 1 - y);
3132 ADD(cr - 1 - x, cr - 1 - y);
3136 ADD(cr - 1 - x, cr - 1 - y);
3137 ADD(cr - 1 - y, cr - 1 - x);
3142 ADD(cr - 1 - x, cr - 1 - y);
3146 ADD(cr - 1 - y, cr - 1 - x);
3155 static char *encode_solve_move(int cr, digit *grid)
3162 * It's surprisingly easy to work out _exactly_ how long this
3163 * string needs to be. To decimal-encode all the numbers from 1
3166 * - every number has a units digit; total is n.
3167 * - all numbers above 9 have a tens digit; total is max(n-9,0).
3168 * - all numbers above 99 have a hundreds digit; total is max(n-99,0).
3172 for (i = 1; i <= cr; i *= 10)
3173 len += max(cr - i + 1, 0);
3174 len += cr; /* don't forget the commas */
3175 len *= cr; /* there are cr rows of these */
3178 * Now len is one bigger than the total size of the
3179 * comma-separated numbers (because we counted an
3180 * additional leading comma). We need to have a leading S
3181 * and a trailing NUL, so we're off by one in total.
3185 ret = snewn(len, char);
3189 for (i = 0; i < cr*cr; i++) {
3190 p += sprintf(p, "%s%d", sep, grid[i]);
3194 assert(p - ret == len);
3199 static void dsf_to_blocks(int *dsf, struct block_structure *blocks,
3200 int min_expected, int max_expected)
3202 int cr = blocks->c * blocks->r, area = cr * cr;
3205 for (i = 0; i < area; i++)
3206 blocks->whichblock[i] = -1;
3207 for (i = 0; i < area; i++) {
3208 int j = dsf_canonify(dsf, i);
3209 if (blocks->whichblock[j] < 0)
3210 blocks->whichblock[j] = nb++;
3211 blocks->whichblock[i] = blocks->whichblock[j];
3213 assert(nb >= min_expected && nb <= max_expected);
3214 blocks->nr_blocks = nb;
3217 static void make_blocks_from_whichblock(struct block_structure *blocks)
3221 for (i = 0; i < blocks->nr_blocks; i++) {
3222 blocks->blocks[i][blocks->max_nr_squares-1] = 0;
3223 blocks->nr_squares[i] = 0;
3225 for (i = 0; i < blocks->area; i++) {
3226 int b = blocks->whichblock[i];
3227 int j = blocks->blocks[b][blocks->max_nr_squares-1]++;
3228 assert(j < blocks->max_nr_squares);
3229 blocks->blocks[b][j] = i;
3230 blocks->nr_squares[b]++;
3234 static char *encode_block_structure_desc(char *p, struct block_structure *blocks)
3237 int c = blocks->c, r = blocks->r, cr = c * r;
3240 * Encode the block structure. We do this by encoding
3241 * the pattern of dividing lines: first we iterate
3242 * over the cr*(cr-1) internal vertical grid lines in
3243 * ordinary reading order, then over the cr*(cr-1)
3244 * internal horizontal ones in transposed reading
3247 * We encode the number of non-lines between the
3248 * lines; _ means zero (two adjacent divisions), a
3249 * means 1, ..., y means 25, and z means 25 non-lines
3250 * _and no following line_ (so that za means 26, zb 27
3253 for (i = 0; i <= 2*cr*(cr-1); i++) {
3254 int x, y, p0, p1, edge;
3256 if (i == 2*cr*(cr-1)) {
3257 edge = TRUE; /* terminating virtual edge */
3259 if (i < cr*(cr-1)) {
3270 edge = (blocks->whichblock[p0] != blocks->whichblock[p1]);
3274 while (currrun > 25)
3275 *p++ = 'z', currrun -= 25;
3277 *p++ = 'a'-1 + currrun;
3287 static char *encode_grid(char *desc, digit *grid, int area)
3293 for (i = 0; i <= area; i++) {
3294 int n = (i < area ? grid[i] : -1);
3301 int c = 'a' - 1 + run;
3305 run -= c - ('a' - 1);
3309 * If there's a number in the very top left or
3310 * bottom right, there's no point putting an
3311 * unnecessary _ before or after it.
3313 if (p > desc && n > 0)
3317 p += sprintf(p, "%d", n);
3325 * Conservatively stimate the number of characters required for
3326 * encoding a grid of a certain area.
3328 static int grid_encode_space (int area)
3331 for (count = 1, t = area; t > 26; t -= 26)
3333 return count * area;
3337 * Conservatively stimate the number of characters required for
3338 * encoding a given blocks structure.
3340 static int blocks_encode_space(struct block_structure *blocks)
3342 int cr = blocks->c * blocks->r, area = cr * cr;
3343 return grid_encode_space(area);
3346 static char *encode_puzzle_desc(const game_params *params, digit *grid,
3347 struct block_structure *blocks,
3349 struct block_structure *kblocks)
3351 int c = params->c, r = params->r, cr = c*r;
3356 space = grid_encode_space(area) + 1;
3358 space += blocks_encode_space(blocks) + 1;
3359 if (params->killer) {
3360 space += blocks_encode_space(kblocks) + 1;
3361 space += grid_encode_space(area) + 1;
3363 desc = snewn(space, char);
3364 p = encode_grid(desc, grid, area);
3368 p = encode_block_structure_desc(p, blocks);
3370 if (params->killer) {
3372 p = encode_block_structure_desc(p, kblocks);
3374 p = encode_grid(p, kgrid, area);
3376 assert(p - desc < space);
3378 desc = sresize(desc, p - desc, char);
3383 static void merge_blocks(struct block_structure *b, int n1, int n2)
3386 /* Move data towards the lower block number. */
3393 /* Merge n2 into n1, and move the last block into n2's position. */
3394 for (i = 0; i < b->nr_squares[n2]; i++)
3395 b->whichblock[b->blocks[n2][i]] = n1;
3396 memcpy(b->blocks[n1] + b->nr_squares[n1], b->blocks[n2],
3397 b->nr_squares[n2] * sizeof **b->blocks);
3398 b->nr_squares[n1] += b->nr_squares[n2];
3400 n1 = b->nr_blocks - 1;
3402 memcpy(b->blocks[n2], b->blocks[n1],
3403 b->nr_squares[n1] * sizeof **b->blocks);
3404 for (i = 0; i < b->nr_squares[n1]; i++)
3405 b->whichblock[b->blocks[n1][i]] = n2;
3406 b->nr_squares[n2] = b->nr_squares[n1];
3411 static int merge_some_cages(struct block_structure *b, int cr, int area,
3412 digit *grid, random_state *rs)
3415 * Make a list of all the pairs of adjacent blocks.
3423 pairs = snewn(b->nr_blocks * b->nr_blocks, struct pair);
3426 for (i = 0; i < b->nr_blocks; i++) {
3427 for (j = i+1; j < b->nr_blocks; j++) {
3430 * Rule the merger out of consideration if it's
3431 * obviously not viable.
3433 if (b->nr_squares[i] + b->nr_squares[j] > b->max_nr_squares)
3434 continue; /* we couldn't merge these anyway */
3437 * See if these two blocks have a pair of squares
3438 * adjacent to each other.
3440 for (k = 0; k < b->nr_squares[i]; k++) {
3441 int xy = b->blocks[i][k];
3442 int y = xy / cr, x = xy % cr;
3443 if ((y > 0 && b->whichblock[xy - cr] == j) ||
3444 (y+1 < cr && b->whichblock[xy + cr] == j) ||
3445 (x > 0 && b->whichblock[xy - 1] == j) ||
3446 (x+1 < cr && b->whichblock[xy + 1] == j)) {
3448 * Yes! Add this pair to our list.
3450 pairs[npairs].b1 = i;
3451 pairs[npairs].b2 = j;
3459 * Now go through that list in random order until we find a pair
3460 * of blocks we can merge.
3462 while (npairs > 0) {
3464 unsigned int digits_found;
3467 * Pick a random pair, and remove it from the list.
3469 i = random_upto(rs, npairs);
3473 pairs[i] = pairs[npairs-1];
3476 /* Guarantee that the merged cage would still be a region. */
3478 for (i = 0; i < b->nr_squares[n1]; i++)
3479 digits_found |= 1 << grid[b->blocks[n1][i]];
3480 for (i = 0; i < b->nr_squares[n2]; i++)
3481 if (digits_found & (1 << grid[b->blocks[n2][i]]))
3483 if (i != b->nr_squares[n2])
3487 * Got one! Do the merge.
3489 merge_blocks(b, n1, n2);
3498 static void compute_kclues(struct block_structure *cages, digit *kclues,
3499 digit *grid, int area)
3502 memset(kclues, 0, area * sizeof *kclues);
3503 for (i = 0; i < cages->nr_blocks; i++) {
3505 for (j = 0; j < area; j++)
3506 if (cages->whichblock[j] == i)
3508 for (j = 0; j < area; j++)
3509 if (cages->whichblock[j] == i)
3516 static struct block_structure *gen_killer_cages(int cr, random_state *rs,
3517 int remove_singletons)
3520 int x, y, area = cr * cr;
3521 int n_singletons = 0;
3522 struct block_structure *b = alloc_block_structure (1, cr, area, cr, area);
3524 for (x = 0; x < area; x++)
3525 b->whichblock[x] = -1;
3527 for (y = 0; y < cr; y++)
3528 for (x = 0; x < cr; x++) {
3531 if (b->whichblock[xy] != -1)
3533 b->whichblock[xy] = nr;
3535 rnd = random_bits(rs, 4);
3536 if (xy + 1 < area && (rnd >= 4 || (!remove_singletons && rnd >= 1))) {
3538 if (x + 1 == cr || b->whichblock[xy2] != -1 ||
3539 (xy + cr < area && random_bits(rs, 1) == 0))
3544 b->whichblock[xy2] = nr;
3551 make_blocks_from_whichblock(b);
3553 for (x = y = 0; x < b->nr_blocks; x++)
3554 if (b->nr_squares[x] == 1)
3556 assert(y == n_singletons);
3558 if (n_singletons > 0 && remove_singletons) {
3560 for (n = 0; n < b->nr_blocks;) {
3561 int xy, x, y, xy2, other;
3562 if (b->nr_squares[n] > 1) {
3566 xy = b->blocks[n][0];
3571 else if (x + 1 < cr && (y + 1 == cr || random_bits(rs, 1) == 0))
3575 other = b->whichblock[xy2];
3577 if (b->nr_squares[other] == 1)
3580 merge_blocks(b, n, other);
3584 assert(n_singletons == 0);
3589 static char *new_game_desc(const game_params *params, random_state *rs,
3590 char **aux, int interactive)
3592 int c = params->c, r = params->r, cr = c*r;
3594 struct block_structure *blocks, *kblocks;
3595 digit *grid, *grid2, *kgrid;
3596 struct xy { int x, y; } *locs;
3599 int coords[16], ncoords;
3601 struct difficulty dlev;
3603 precompute_sum_bits();
3606 * Adjust the maximum difficulty level to be consistent with
3607 * the puzzle size: all 2x2 puzzles appear to be Trivial
3608 * (DIFF_BLOCK) so we cannot hold out for even a Basic
3609 * (DIFF_SIMPLE) one.
3611 dlev.maxdiff = params->diff;
3612 dlev.maxkdiff = params->kdiff;
3613 if (c == 2 && r == 2)
3614 dlev.maxdiff = DIFF_BLOCK;
3616 grid = snewn(area, digit);
3617 locs = snewn(area, struct xy);
3618 grid2 = snewn(area, digit);
3620 blocks = alloc_block_structure (c, r, area, cr, cr);
3623 kgrid = (params->killer) ? snewn(area, digit) : NULL;
3625 #ifdef STANDALONE_SOLVER
3626 assert(!"This should never happen, so we don't need to create blocknames");
3630 * Loop until we get a grid of the required difficulty. This is
3631 * nasty, but it seems to be unpleasantly hard to generate
3632 * difficult grids otherwise.
3636 * Generate a random solved state, starting by
3637 * constructing the block structure.
3639 if (r == 1) { /* jigsaw mode */
3640 int *dsf = divvy_rectangle(cr, cr, cr, rs);
3642 dsf_to_blocks (dsf, blocks, cr, cr);
3645 } else { /* basic Sudoku mode */
3646 for (y = 0; y < cr; y++)
3647 for (x = 0; x < cr; x++)
3648 blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
3650 make_blocks_from_whichblock(blocks);
3652 if (params->killer) {
3653 if (kblocks) free_block_structure(kblocks);
3654 kblocks = gen_killer_cages(cr, rs, params->kdiff > DIFF_KSINGLE);
3657 if (!gridgen(cr, blocks, kblocks, params->xtype, grid, rs, area*area))
3659 assert(check_valid(cr, blocks, kblocks, NULL, params->xtype, grid));
3662 * Save the solved grid in aux.
3666 * We might already have written *aux the last time we
3667 * went round this loop, in which case we should free
3668 * the old aux before overwriting it with the new one.
3674 *aux = encode_solve_move(cr, grid);
3678 * Now we have a solved grid. For normal puzzles, we start removing
3679 * things from it while preserving solubility. Killer puzzles are
3680 * different: we just pass the empty grid to the solver, and use
3681 * the puzzle if it comes back solved.
3684 if (params->killer) {
3685 struct block_structure *good_cages = NULL;
3686 struct block_structure *last_cages = NULL;
3689 memcpy(grid2, grid, area);
3692 compute_kclues(kblocks, kgrid, grid2, area);
3694 memset(grid, 0, area * sizeof *grid);
3695 solver(cr, blocks, kblocks, params->xtype, grid, kgrid, &dlev);
3696 if (dlev.diff == dlev.maxdiff && dlev.kdiff == dlev.maxkdiff) {
3698 * We have one that matches our difficulty. Store it for
3699 * later, but keep going.
3702 free_block_structure(good_cages);
3704 good_cages = dup_block_structure(kblocks);
3705 if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3707 } else if (dlev.diff > dlev.maxdiff || dlev.kdiff > dlev.maxkdiff) {
3709 * Give up after too many tries and either use the good one we
3710 * found, or generate a new grid.
3715 * The difficulty level got too high. If we have a good
3716 * one, use it, otherwise go back to the last one that
3717 * was at a lower difficulty and restart the process from
3720 if (good_cages != NULL) {
3721 free_block_structure(kblocks);
3722 kblocks = dup_block_structure(good_cages);
3723 if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3726 if (last_cages == NULL)
3728 free_block_structure(kblocks);
3729 kblocks = last_cages;
3734 free_block_structure(last_cages);
3735 last_cages = dup_block_structure(kblocks);
3736 if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3741 free_block_structure(last_cages);
3742 if (good_cages != NULL) {
3743 free_block_structure(kblocks);
3744 kblocks = good_cages;
3745 compute_kclues(kblocks, kgrid, grid2, area);
3746 memset(grid, 0, area * sizeof *grid);
3753 * Find the set of equivalence classes of squares permitted
3754 * by the selected symmetry. We do this by enumerating all
3755 * the grid squares which have no symmetric companion
3756 * sorting lower than themselves.
3759 for (y = 0; y < cr; y++)
3760 for (x = 0; x < cr; x++) {
3764 ncoords = symmetries(params, x, y, coords, params->symm);
3765 for (j = 0; j < ncoords; j++)
3766 if (coords[2*j+1]*cr+coords[2*j] < i)
3776 * Now shuffle that list.
3778 shuffle(locs, nlocs, sizeof(*locs), rs);
3781 * Now loop over the shuffled list and, for each element,
3782 * see whether removing that element (and its reflections)
3783 * from the grid will still leave the grid soluble.
3785 for (i = 0; i < nlocs; i++) {
3789 memcpy(grid2, grid, area);
3790 ncoords = symmetries(params, x, y, coords, params->symm);
3791 for (j = 0; j < ncoords; j++)
3792 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
3794 solver(cr, blocks, kblocks, params->xtype, grid2, kgrid, &dlev);
3795 if (dlev.diff <= dlev.maxdiff &&
3796 (!params->killer || dlev.kdiff <= dlev.maxkdiff)) {
3797 for (j = 0; j < ncoords; j++)
3798 grid[coords[2*j+1]*cr+coords[2*j]] = 0;
3802 memcpy(grid2, grid, area);
3804 solver(cr, blocks, kblocks, params->xtype, grid2, kgrid, &dlev);
3805 if (dlev.diff == dlev.maxdiff &&
3806 (!params->killer || dlev.kdiff == dlev.maxkdiff))
3807 break; /* found one! */
3814 * Now we have the grid as it will be presented to the user.
3815 * Encode it in a game desc.
3817 desc = encode_puzzle_desc(params, grid, blocks, kgrid, kblocks);
3820 free_block_structure(blocks);
3821 if (params->killer) {
3822 free_block_structure(kblocks);
3829 static const char *spec_to_grid(const char *desc, digit *grid, int area)
3832 while (*desc && *desc != ',') {
3834 if (n >= 'a' && n <= 'z') {
3835 int run = n - 'a' + 1;
3836 assert(i + run <= area);
3839 } else if (n == '_') {
3841 } else if (n > '0' && n <= '9') {
3843 grid[i++] = atoi(desc-1);
3844 while (*desc >= '0' && *desc <= '9')
3847 assert(!"We can't get here");
3855 * Create a DSF from a spec found in *pdesc. Update this to point past the
3856 * end of the block spec, and return an error string or NULL if everything
3857 * is OK. The DSF is stored in *PDSF.
3859 static const char *spec_to_dsf(const char **pdesc, int **pdsf,
3862 const char *desc = *pdesc;
3866 *pdsf = dsf = snew_dsf(area);
3868 while (*desc && *desc != ',') {
3873 else if (*desc >= 'a' && *desc <= 'z')
3874 c = *desc - 'a' + 1;
3877 return "Invalid character in game description";
3881 adv = (c != 26); /* 'z' is a special case */
3887 * Non-edge; merge the two dsf classes on either
3890 if (pos >= 2*cr*(cr-1)) {
3892 return "Too much data in block structure specification";
3895 if (pos < cr*(cr-1)) {
3901 int x = pos/(cr-1) - cr;
3906 dsf_merge(dsf, p0, p1);
3916 * When desc is exhausted, we expect to have gone exactly
3917 * one space _past_ the end of the grid, due to the dummy
3920 if (pos != 2*cr*(cr-1)+1) {
3922 return "Not enough data in block structure specification";
3928 static const char *validate_grid_desc(const char **pdesc, int range, int area)
3930 const char *desc = *pdesc;
3932 while (*desc && *desc != ',') {
3934 if (n >= 'a' && n <= 'z') {
3935 squares += n - 'a' + 1;
3936 } else if (n == '_') {
3938 } else if (n > '0' && n <= '9') {
3939 int val = atoi(desc-1);
3940 if (val < 1 || val > range)
3941 return "Out-of-range number in game description";
3943 while (*desc >= '0' && *desc <= '9')
3946 return "Invalid character in game description";
3950 return "Not enough data to fill grid";
3953 return "Too much data to fit in grid";
3958 static const char *validate_block_desc(const char **pdesc, int cr, int area,
3959 int min_nr_blocks, int max_nr_blocks,
3960 int min_nr_squares, int max_nr_squares)
3965 err = spec_to_dsf(pdesc, &dsf, cr, area);
3970 if (min_nr_squares == max_nr_squares) {
3971 assert(min_nr_blocks == max_nr_blocks);
3972 assert(min_nr_blocks * min_nr_squares == area);
3975 * Now we've got our dsf. Verify that it matches
3979 int *canons, *counts;
3980 int i, j, c, ncanons = 0;
3982 canons = snewn(max_nr_blocks, int);
3983 counts = snewn(max_nr_blocks, int);
3985 for (i = 0; i < area; i++) {
3986 j = dsf_canonify(dsf, i);
3988 for (c = 0; c < ncanons; c++)
3989 if (canons[c] == j) {
3991 if (counts[c] > max_nr_squares) {
3995 return "A jigsaw block is too big";
4001 if (ncanons >= max_nr_blocks) {
4005 return "Too many distinct jigsaw blocks";
4007 canons[ncanons] = j;
4008 counts[ncanons] = 1;
4013 if (ncanons < min_nr_blocks) {
4017 return "Not enough distinct jigsaw blocks";
4019 for (c = 0; c < ncanons; c++) {
4020 if (counts[c] < min_nr_squares) {
4024 return "A jigsaw block is too small";
4035 static const char *validate_desc(const game_params *params, const char *desc)
4037 int cr = params->c * params->r, area = cr*cr;
4040 err = validate_grid_desc(&desc, cr, area);
4044 if (params->r == 1) {
4046 * Now we expect a suffix giving the jigsaw block
4047 * structure. Parse it and validate that it divides the
4048 * grid into the right number of regions which are the
4052 return "Expected jigsaw block structure in game description";
4054 err = validate_block_desc(&desc, cr, area, cr, cr, cr, cr);
4059 if (params->killer) {
4061 return "Expected killer block structure in game description";
4063 err = validate_block_desc(&desc, cr, area, cr, area, 2, cr);
4067 return "Expected killer clue grid in game description";
4069 err = validate_grid_desc(&desc, cr * area, area);
4074 return "Unexpected data at end of game description";
4079 static game_state *new_game(midend *me, const game_params *params,
4082 game_state *state = snew(game_state);
4083 int c = params->c, r = params->r, cr = c*r, area = cr * cr;
4086 precompute_sum_bits();
4089 state->xtype = params->xtype;
4090 state->killer = params->killer;
4092 state->grid = snewn(area, digit);
4093 state->pencil = snewn(area * cr, unsigned char);
4094 memset(state->pencil, 0, area * cr);
4095 state->immutable = snewn(area, unsigned char);
4096 memset(state->immutable, FALSE, area);
4098 state->blocks = alloc_block_structure (c, r, area, cr, cr);
4100 if (params->killer) {
4101 state->kblocks = alloc_block_structure (c, r, area, cr, area);
4102 state->kgrid = snewn(area, digit);
4104 state->kblocks = NULL;
4105 state->kgrid = NULL;
4107 state->completed = state->cheated = FALSE;
4109 desc = spec_to_grid(desc, state->grid, area);
4110 for (i = 0; i < area; i++)
4111 if (state->grid[i] != 0)
4112 state->immutable[i] = TRUE;
4117 assert(*desc == ',');
4119 err = spec_to_dsf(&desc, &dsf, cr, area);
4120 assert(err == NULL);
4121 dsf_to_blocks(dsf, state->blocks, cr, cr);
4126 for (y = 0; y < cr; y++)
4127 for (x = 0; x < cr; x++)
4128 state->blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
4130 make_blocks_from_whichblock(state->blocks);
4132 if (params->killer) {
4135 assert(*desc == ',');
4137 err = spec_to_dsf(&desc, &dsf, cr, area);
4138 assert(err == NULL);
4139 dsf_to_blocks(dsf, state->kblocks, cr, area);
4141 make_blocks_from_whichblock(state->kblocks);
4143 assert(*desc == ',');
4145 desc = spec_to_grid(desc, state->kgrid, area);
4149 #ifdef STANDALONE_SOLVER
4151 * Set up the block names for solver diagnostic output.
4154 char *p = (char *)(state->blocks->blocknames + cr);
4157 for (i = 0; i < area; i++) {
4158 int j = state->blocks->whichblock[i];
4159 if (!state->blocks->blocknames[j]) {
4160 state->blocks->blocknames[j] = p;
4161 p += 1 + sprintf(p, "starting at (%d,%d)",
4162 1 + i%cr, 1 + i/cr);
4167 for (by = 0; by < r; by++)
4168 for (bx = 0; bx < c; bx++) {
4169 state->blocks->blocknames[by*c+bx] = p;
4170 p += 1 + sprintf(p, "(%d,%d)", bx+1, by+1);
4173 assert(p - (char *)state->blocks->blocknames < (int)(cr*(sizeof(char *)+80)));
4174 for (i = 0; i < cr; i++)
4175 assert(state->blocks->blocknames[i]);
4182 static game_state *dup_game(const game_state *state)
4184 game_state *ret = snew(game_state);
4185 int cr = state->cr, area = cr * cr;
4187 ret->cr = state->cr;
4188 ret->xtype = state->xtype;
4189 ret->killer = state->killer;
4191 ret->blocks = state->blocks;
4192 ret->blocks->refcount++;
4194 ret->kblocks = state->kblocks;
4196 ret->kblocks->refcount++;
4198 ret->grid = snewn(area, digit);
4199 memcpy(ret->grid, state->grid, area);
4201 if (state->killer) {
4202 ret->kgrid = snewn(area, digit);
4203 memcpy(ret->kgrid, state->kgrid, area);
4207 ret->pencil = snewn(area * cr, unsigned char);
4208 memcpy(ret->pencil, state->pencil, area * cr);
4210 ret->immutable = snewn(area, unsigned char);
4211 memcpy(ret->immutable, state->immutable, area);
4213 ret->completed = state->completed;
4214 ret->cheated = state->cheated;
4219 static void free_game(game_state *state)
4221 free_block_structure(state->blocks);
4223 free_block_structure(state->kblocks);
4225 sfree(state->immutable);
4226 sfree(state->pencil);
4228 if (state->kgrid) sfree(state->kgrid);
4232 static char *solve_game(const game_state *state, const game_state *currstate,
4233 const char *ai, const char **error)
4238 struct difficulty dlev;
4241 * If we already have the solution in ai, save ourselves some
4247 grid = snewn(cr*cr, digit);
4248 memcpy(grid, state->grid, cr*cr);
4249 dlev.maxdiff = DIFF_RECURSIVE;
4250 dlev.maxkdiff = DIFF_KINTERSECT;
4251 solver(cr, state->blocks, state->kblocks, state->xtype, grid,
4252 state->kgrid, &dlev);
4256 if (dlev.diff == DIFF_IMPOSSIBLE)
4257 *error = "No solution exists for this puzzle";
4258 else if (dlev.diff == DIFF_AMBIGUOUS)
4259 *error = "Multiple solutions exist for this puzzle";
4266 ret = encode_solve_move(cr, grid);
4273 static char *grid_text_format(int cr, struct block_structure *blocks,
4274 int xtype, digit *grid)
4278 int totallen, linelen, nlines;
4282 * For non-jigsaw Sudoku, we format in the way we always have,
4283 * by having the digits unevenly spaced so that the dividing
4292 * For jigsaw puzzles, however, we must leave space between
4293 * _all_ pairs of digits for an optional dividing line, so we
4294 * have to move to the rather ugly
4304 * We deal with both cases using the same formatting code; we
4305 * simply invent a vmod value such that there's a vertical
4306 * dividing line before column i iff i is divisible by vmod
4307 * (so it's r in the first case and 1 in the second), and hmod
4308 * likewise for horizontal dividing lines.
4311 if (blocks->r != 1) {
4319 * Line length: we have cr digits, each with a space after it,
4320 * and (cr-1)/vmod dividing lines, each with a space after it.
4321 * The final space is replaced by a newline, but that doesn't
4322 * affect the length.
4324 linelen = 2*(cr + (cr-1)/vmod);
4327 * Number of lines: we have cr rows of digits, and (cr-1)/hmod
4330 nlines = cr + (cr-1)/hmod;
4333 * Allocate the space.
4335 totallen = linelen * nlines;
4336 ret = snewn(totallen+1, char); /* leave room for terminating NUL */
4342 for (y = 0; y < cr; y++) {
4346 for (x = 0; x < cr; x++) {
4350 digit d = grid[y*cr+x];
4354 * Empty space: we usually write a dot, but we'll
4355 * highlight spaces on the X-diagonals (in X mode)
4356 * by using underscores instead.
4358 if (xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x)))
4362 } else if (d <= 9) {
4379 * Optional dividing line.
4381 if (blocks->whichblock[y*cr+x] != blocks->whichblock[y*cr+x+1])
4388 if (y == cr-1 || (y+1) % hmod)
4394 for (x = 0; x < cr; x++) {
4399 * Division between two squares. This varies
4400 * complicatedly in length.
4402 dwid = 2; /* digit and its following space */
4404 dwid--; /* no following space at end of line */
4405 if (x > 0 && x % vmod == 0)
4406 dwid++; /* preceding space after a divider */
4408 if (blocks->whichblock[y*cr+x] != blocks->whichblock[(y+1)*cr+x])
4425 * Corner square. This is:
4426 * - a space if all four surrounding squares are in
4428 * - a vertical line if the two left ones are in one
4429 * block and the two right in another
4430 * - a horizontal line if the two top ones are in one
4431 * block and the two bottom in another
4432 * - a plus sign in all other cases. (If we had a
4433 * richer character set available we could break
4434 * this case up further by doing fun things with
4435 * line-drawing T-pieces.)
4437 tl = blocks->whichblock[y*cr+x];
4438 tr = blocks->whichblock[y*cr+x+1];
4439 bl = blocks->whichblock[(y+1)*cr+x];
4440 br = blocks->whichblock[(y+1)*cr+x+1];
4442 if (tl == tr && tr == bl && bl == br)
4444 else if (tl == bl && tr == br)
4446 else if (tl == tr && bl == br)
4455 assert(p - ret == totallen);
4460 static int game_can_format_as_text_now(const game_params *params)
4463 * Formatting Killer puzzles as text is currently unsupported. I
4464 * can't think of any sensible way of doing it which doesn't
4465 * involve expanding the puzzle to such a large scale as to make
4473 static char *game_text_format(const game_state *state)
4475 assert(!state->kblocks);
4476 return grid_text_format(state->cr, state->blocks, state->xtype,
4482 * These are the coordinates of the currently highlighted
4483 * square on the grid, if hshow = 1.
4487 * This indicates whether the current highlight is a
4488 * pencil-mark one or a real one.
4492 * This indicates whether or not we're showing the highlight
4493 * (used to be hx = hy = -1); important so that when we're
4494 * using the cursor keys it doesn't keep coming back at a
4495 * fixed position. When hshow = 1, pressing a valid number
4496 * or letter key or Space will enter that number or letter in the grid.
4500 * This indicates whether we're using the highlight as a cursor;
4501 * it means that it doesn't vanish on a keypress, and that it is
4502 * allowed on immutable squares.
4507 static game_ui *new_ui(const game_state *state)
4509 game_ui *ui = snew(game_ui);
4511 ui->hx = ui->hy = 0;
4512 ui->hpencil = ui->hshow = ui->hcursor = 0;
4517 static void free_ui(game_ui *ui)
4522 static char *encode_ui(const game_ui *ui)
4527 static void decode_ui(game_ui *ui, const char *encoding)
4531 static void game_changed_state(game_ui *ui, const game_state *oldstate,
4532 const game_state *newstate)
4534 int cr = newstate->cr;
4536 * We prevent pencil-mode highlighting of a filled square, unless
4537 * we're using the cursor keys. So if the user has just filled in
4538 * a square which we had a pencil-mode highlight in (by Undo, or
4539 * by Redo, or by Solve), then we cancel the highlight.
4541 if (ui->hshow && ui->hpencil && !ui->hcursor &&
4542 newstate->grid[ui->hy * cr + ui->hx] != 0) {
4547 struct game_drawstate {
4552 unsigned char *pencil;
4554 /* This is scratch space used within a single call to game_redraw. */
4555 int nregions, *entered_items;
4558 static char *interpret_move(const game_state *state, game_ui *ui,
4559 const game_drawstate *ds,
4560 int x, int y, int button)
4566 button &= ~MOD_MASK;
4568 tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
4569 ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
4571 if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
4572 if (button == LEFT_BUTTON) {
4573 if (state->immutable[ty*cr+tx]) {
4575 } else if (tx == ui->hx && ty == ui->hy &&
4576 ui->hshow && ui->hpencil == 0) {
4587 if (button == RIGHT_BUTTON) {
4589 * Pencil-mode highlighting for non filled squares.
4591 if (state->grid[ty*cr+tx] == 0) {
4592 if (tx == ui->hx && ty == ui->hy &&
4593 ui->hshow && ui->hpencil) {
4608 if (IS_CURSOR_MOVE(button)) {
4609 move_cursor(button, &ui->hx, &ui->hy, cr, cr, 0);
4610 ui->hshow = ui->hcursor = 1;
4614 (button == CURSOR_SELECT)) {
4615 ui->hpencil = 1 - ui->hpencil;
4621 ((button >= '0' && button <= '9' && button - '0' <= cr) ||
4622 (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
4623 (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
4624 button == CURSOR_SELECT2 || button == '\b')) {
4625 int n = button - '0';
4626 if (button >= 'A' && button <= 'Z')
4627 n = button - 'A' + 10;
4628 if (button >= 'a' && button <= 'z')
4629 n = button - 'a' + 10;
4630 if (button == CURSOR_SELECT2 || button == '\b')
4634 * Can't overwrite this square. This can only happen here
4635 * if we're using the cursor keys.
4637 if (state->immutable[ui->hy*cr+ui->hx])
4641 * Can't make pencil marks in a filled square. Again, this
4642 * can only become highlighted if we're using cursor keys.
4644 if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
4647 sprintf(buf, "%c%d,%d,%d",
4648 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
4650 if (!ui->hcursor) ui->hshow = 0;
4655 if (button == 'M' || button == 'm')
4661 static game_state *execute_move(const game_state *from, const char *move)
4667 if (move[0] == 'S') {
4670 ret = dup_game(from);
4671 ret->completed = ret->cheated = TRUE;
4674 for (n = 0; n < cr*cr; n++) {
4675 ret->grid[n] = atoi(p);
4677 if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
4682 while (*p && isdigit((unsigned char)*p)) p++;
4687 } else if ((move[0] == 'P' || move[0] == 'R') &&
4688 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
4689 x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
4691 ret = dup_game(from);
4692 if (move[0] == 'P' && n > 0) {
4693 int index = (y*cr+x) * cr + (n-1);
4694 ret->pencil[index] = !ret->pencil[index];
4696 ret->grid[y*cr+x] = n;
4697 memset(ret->pencil + (y*cr+x)*cr, 0, cr);
4700 * We've made a real change to the grid. Check to see
4701 * if the game has been completed.
4703 if (!ret->completed && check_valid(
4704 cr, ret->blocks, ret->kblocks, ret->kgrid,
4705 ret->xtype, ret->grid)) {
4706 ret->completed = TRUE;
4710 } else if (move[0] == 'M') {
4712 * Fill in absolutely all pencil marks in unfilled squares,
4713 * for those who like to play by the rigorous approach of
4714 * starting off in that state and eliminating things.
4716 ret = dup_game(from);
4717 for (y = 0; y < cr; y++) {
4718 for (x = 0; x < cr; x++) {
4719 if (!ret->grid[y*cr+x]) {
4720 memset(ret->pencil + (y*cr+x)*cr, 1, cr);
4726 return NULL; /* couldn't parse move string */
4729 /* ----------------------------------------------------------------------
4733 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
4734 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
4736 static void game_compute_size(const game_params *params, int tilesize,
4739 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
4740 struct { int tilesize; } ads, *ds = &ads;
4741 ads.tilesize = tilesize;
4743 *x = SIZE(params->c * params->r);
4744 *y = SIZE(params->c * params->r);
4747 static void game_set_size(drawing *dr, game_drawstate *ds,
4748 const game_params *params, int tilesize)
4750 ds->tilesize = tilesize;
4753 static float *game_colours(frontend *fe, int *ncolours)
4755 float *ret = snewn(3 * NCOLOURS, float);
4757 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
4759 ret[COL_XDIAGONALS * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
4760 ret[COL_XDIAGONALS * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
4761 ret[COL_XDIAGONALS * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
4763 ret[COL_GRID * 3 + 0] = 0.0F;
4764 ret[COL_GRID * 3 + 1] = 0.0F;
4765 ret[COL_GRID * 3 + 2] = 0.0F;
4767 ret[COL_CLUE * 3 + 0] = 0.0F;
4768 ret[COL_CLUE * 3 + 1] = 0.0F;
4769 ret[COL_CLUE * 3 + 2] = 0.0F;
4771 ret[COL_USER * 3 + 0] = 0.0F;
4772 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
4773 ret[COL_USER * 3 + 2] = 0.0F;
4775 ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
4776 ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
4777 ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
4779 ret[COL_ERROR * 3 + 0] = 1.0F;
4780 ret[COL_ERROR * 3 + 1] = 0.0F;
4781 ret[COL_ERROR * 3 + 2] = 0.0F;
4783 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
4784 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
4785 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
4787 ret[COL_KILLER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
4788 ret[COL_KILLER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
4789 ret[COL_KILLER * 3 + 2] = 0.1F * ret[COL_BACKGROUND * 3 + 2];
4791 *ncolours = NCOLOURS;
4795 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
4797 struct game_drawstate *ds = snew(struct game_drawstate);
4800 ds->started = FALSE;
4802 ds->xtype = state->xtype;
4803 ds->grid = snewn(cr*cr, digit);
4804 memset(ds->grid, cr+2, cr*cr);
4805 ds->pencil = snewn(cr*cr*cr, digit);
4806 memset(ds->pencil, 0, cr*cr*cr);
4807 ds->hl = snewn(cr*cr, unsigned char);
4808 memset(ds->hl, 0, cr*cr);
4810 * ds->entered_items needs one row of cr entries per entity in
4811 * which digits may not be duplicated. That's one for each row,
4812 * each column, each block, each diagonal, and each Killer cage.
4814 ds->nregions = cr*3 + 2;
4816 ds->nregions += state->kblocks->nr_blocks;
4817 ds->entered_items = snewn(cr * ds->nregions, int);
4818 ds->tilesize = 0; /* not decided yet */
4822 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
4827 sfree(ds->entered_items);
4831 static void draw_number(drawing *dr, game_drawstate *ds,
4832 const game_state *state, int x, int y, int hl)
4837 int col_killer = (hl & 32 ? COL_ERROR : COL_KILLER);
4840 if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
4841 ds->hl[y*cr+x] == hl &&
4842 !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
4843 return; /* no change required */
4845 tx = BORDER + x * TILE_SIZE + 1 + GRIDEXTRA;
4846 ty = BORDER + y * TILE_SIZE + 1 + GRIDEXTRA;
4850 cw = tw = TILE_SIZE-1-2*GRIDEXTRA;
4851 ch = th = TILE_SIZE-1-2*GRIDEXTRA;
4853 if (x > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x-1])
4854 cx -= GRIDEXTRA, cw += GRIDEXTRA;
4855 if (x+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x+1])
4857 if (y > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y-1)*cr+x])
4858 cy -= GRIDEXTRA, ch += GRIDEXTRA;
4859 if (y+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y+1)*cr+x])
4862 clip(dr, cx, cy, cw, ch);
4864 /* background needs erasing */
4865 draw_rect(dr, cx, cy, cw, ch,
4866 ((hl & 15) == 1 ? COL_HIGHLIGHT :
4867 (ds->xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x))) ? COL_XDIAGONALS :
4871 * Draw the corners of thick lines in corner-adjacent squares,
4872 * which jut into this square by one pixel.
4874 if (x > 0 && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x-1])
4875 draw_rect(dr, tx-GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4876 if (x+1 < cr && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x+1])
4877 draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4878 if (x > 0 && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x-1])
4879 draw_rect(dr, tx-GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4880 if (x+1 < cr && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x+1])
4881 draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4883 /* pencil-mode highlight */
4884 if ((hl & 15) == 2) {
4888 coords[2] = cx+cw/2;
4891 coords[5] = cy+ch/2;
4892 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
4895 if (state->kblocks) {
4896 int t = GRIDEXTRA * 3;
4897 int kcx, kcy, kcw, kch;
4899 int has_left = 0, has_right = 0, has_top = 0, has_bottom = 0;
4902 * In non-jigsaw mode, the Killer cages are placed at a
4903 * fixed offset from the outer edge of the cell dividing
4904 * lines, so that they look right whether those lines are
4905 * thick or thin. In jigsaw mode, however, doing this will
4906 * sometimes cause the cage outlines in adjacent squares to
4907 * fail to match up with each other, so we must offset a
4908 * fixed amount from the _centre_ of the cell dividing
4911 if (state->blocks->r == 1) {
4928 * First, draw the lines dividing this area from neighbouring
4931 if (x == 0 || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[y*cr+x-1])
4932 has_left = 1, kl += t;
4933 if (x+1 >= cr || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[y*cr+x+1])
4934 has_right = 1, kr -= t;
4935 if (y == 0 || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x])
4936 has_top = 1, kt += t;
4937 if (y+1 >= cr || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x])
4938 has_bottom = 1, kb -= t;
4940 draw_line(dr, kl, kt, kr, kt, col_killer);
4942 draw_line(dr, kl, kb, kr, kb, col_killer);
4944 draw_line(dr, kl, kt, kl, kb, col_killer);
4946 draw_line(dr, kr, kt, kr, kb, col_killer);
4948 * Now, take care of the corners (just as for the normal borders).
4949 * We only need a corner if there wasn't a full edge.
4951 if (x > 0 && y > 0 && !has_left && !has_top
4952 && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x-1])
4954 draw_line(dr, kl, kt + t, kl + t, kt + t, col_killer);
4955 draw_line(dr, kl + t, kt, kl + t, kt + t, col_killer);
4957 if (x+1 < cr && y > 0 && !has_right && !has_top
4958 && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x+1])
4960 draw_line(dr, kcx + kcw - t, kt + t, kcx + kcw, kt + t, col_killer);
4961 draw_line(dr, kcx + kcw - t, kt, kcx + kcw - t, kt + t, col_killer);
4963 if (x > 0 && y+1 < cr && !has_left && !has_bottom
4964 && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x-1])
4966 draw_line(dr, kl, kcy + kch - t, kl + t, kcy + kch - t, col_killer);
4967 draw_line(dr, kl + t, kcy + kch - t, kl + t, kcy + kch, col_killer);
4969 if (x+1 < cr && y+1 < cr && !has_right && !has_bottom
4970 && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x+1])
4972 draw_line(dr, kcx + kcw - t, kcy + kch - t, kcx + kcw - t, kcy + kch, col_killer);
4973 draw_line(dr, kcx + kcw - t, kcy + kch - t, kcx + kcw, kcy + kch - t, col_killer);
4978 if (state->killer && state->kgrid[y*cr+x]) {
4979 sprintf (str, "%d", state->kgrid[y*cr+x]);
4980 draw_text(dr, tx + GRIDEXTRA * 4, ty + GRIDEXTRA * 4 + TILE_SIZE/4,
4981 FONT_VARIABLE, TILE_SIZE/4, ALIGN_VNORMAL | ALIGN_HLEFT,
4985 /* new number needs drawing? */
4986 if (state->grid[y*cr+x]) {
4988 str[0] = state->grid[y*cr+x] + '0';
4990 str[0] += 'a' - ('9'+1);
4991 draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
4992 FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
4993 state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
4998 int pw, ph, minph, pbest, fontsize;
5000 /* Count the pencil marks required. */
5001 for (i = npencil = 0; i < cr; i++)
5002 if (state->pencil[(y*cr+x)*cr+i])
5009 * Determine the bounding rectangle within which we're going
5010 * to put the pencil marks.
5012 /* Start with the whole square */
5013 pl = tx + GRIDEXTRA;
5014 pr = pl + TILE_SIZE - GRIDEXTRA;
5015 pt = ty + GRIDEXTRA;
5016 pb = pt + TILE_SIZE - GRIDEXTRA;
5017 if (state->killer) {
5019 * Make space for the Killer cages. We do this
5020 * unconditionally, for uniformity between squares,
5021 * rather than making it depend on whether a Killer
5022 * cage edge is actually present on any given side.
5024 pl += GRIDEXTRA * 3;
5025 pr -= GRIDEXTRA * 3;
5026 pt += GRIDEXTRA * 3;
5027 pb -= GRIDEXTRA * 3;
5028 if (state->kgrid[y*cr+x] != 0) {
5029 /* Make further space for the Killer number. */
5036 * We arrange our pencil marks in a grid layout, with
5037 * the number of rows and columns adjusted to allow the
5038 * maximum font size.
5040 * So now we work out what the grid size ought to be.
5045 for (pw = 3; pw < max(npencil,4); pw++) {
5048 ph = (npencil + pw - 1) / pw;
5049 ph = max(ph, minph);
5050 fw = (pr - pl) / (float)pw;
5051 fh = (pb - pt) / (float)ph;
5053 if (fs > bestsize) {
5060 ph = (npencil + pw - 1) / pw;
5061 ph = max(ph, minph);
5064 * Now we've got our grid dimensions, work out the pixel
5065 * size of a grid element, and round it to the nearest
5066 * pixel. (We don't want rounding errors to make the
5067 * grid look uneven at low pixel sizes.)
5069 fontsize = min((pr - pl) / pw, (pb - pt) / ph);
5072 * Centre the resulting figure in the square.
5074 pl = tx + (TILE_SIZE - fontsize * pw) / 2;
5075 pt = ty + (TILE_SIZE - fontsize * ph) / 2;
5078 * And move it down a bit if it's collided with the
5079 * Killer cage number.
5081 if (state->killer && state->kgrid[y*cr+x] != 0) {
5082 pt = max(pt, ty + GRIDEXTRA * 3 + TILE_SIZE/4);
5086 * Now actually draw the pencil marks.
5088 for (i = j = 0; i < cr; i++)
5089 if (state->pencil[(y*cr+x)*cr+i]) {
5090 int dx = j % pw, dy = j / pw;
5095 str[0] += 'a' - ('9'+1);
5096 draw_text(dr, pl + fontsize * (2*dx+1) / 2,
5097 pt + fontsize * (2*dy+1) / 2,
5098 FONT_VARIABLE, fontsize,
5099 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
5107 draw_update(dr, cx, cy, cw, ch);
5109 ds->grid[y*cr+x] = state->grid[y*cr+x];
5110 memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
5111 ds->hl[y*cr+x] = hl;
5114 static void game_redraw(drawing *dr, game_drawstate *ds,
5115 const game_state *oldstate, const game_state *state,
5116 int dir, const game_ui *ui,
5117 float animtime, float flashtime)
5124 * The initial contents of the window are not guaranteed
5125 * and can vary with front ends. To be on the safe side,
5126 * all games should start by drawing a big
5127 * background-colour rectangle covering the whole window.
5129 draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
5132 * Draw the grid. We draw it as a big thick rectangle of
5133 * COL_GRID initially; individual calls to draw_number()
5134 * will poke the right-shaped holes in it.
5136 draw_rect(dr, BORDER-GRIDEXTRA, BORDER-GRIDEXTRA,
5137 cr*TILE_SIZE+1+2*GRIDEXTRA, cr*TILE_SIZE+1+2*GRIDEXTRA,
5142 * This array is used to keep track of rows, columns and boxes
5143 * which contain a number more than once.
5145 for (x = 0; x < cr * ds->nregions; x++)
5146 ds->entered_items[x] = 0;
5147 for (x = 0; x < cr; x++)
5148 for (y = 0; y < cr; y++) {
5149 digit d = state->grid[y*cr+x];
5154 ds->entered_items[x*cr+d-1]++;
5157 ds->entered_items[(y+cr)*cr+d-1]++;
5160 box = state->blocks->whichblock[y*cr+x];
5161 ds->entered_items[(box+2*cr)*cr+d-1]++;
5165 if (ondiag0(y*cr+x))
5166 ds->entered_items[(3*cr)*cr+d-1]++;
5167 if (ondiag1(y*cr+x))
5168 ds->entered_items[(3*cr+1)*cr+d-1]++;
5172 if (state->kblocks) {
5173 kbox = state->kblocks->whichblock[y*cr+x];
5174 ds->entered_items[(kbox+3*cr+2)*cr+d-1]++;
5180 * Draw any numbers which need redrawing.
5182 for (x = 0; x < cr; x++) {
5183 for (y = 0; y < cr; y++) {
5185 digit d = state->grid[y*cr+x];
5187 if (flashtime > 0 &&
5188 (flashtime <= FLASH_TIME/3 ||
5189 flashtime >= FLASH_TIME*2/3))
5192 /* Highlight active input areas. */
5193 if (x == ui->hx && y == ui->hy && ui->hshow)
5194 highlight = ui->hpencil ? 2 : 1;
5196 /* Mark obvious errors (ie, numbers which occur more than once
5197 * in a single row, column, or box). */
5198 if (d && (ds->entered_items[x*cr+d-1] > 1 ||
5199 ds->entered_items[(y+cr)*cr+d-1] > 1 ||
5200 ds->entered_items[(state->blocks->whichblock[y*cr+x]
5201 +2*cr)*cr+d-1] > 1 ||
5202 (ds->xtype && ((ondiag0(y*cr+x) &&
5203 ds->entered_items[(3*cr)*cr+d-1] > 1) ||
5205 ds->entered_items[(3*cr+1)*cr+d-1]>1)))||
5207 ds->entered_items[(state->kblocks->whichblock[y*cr+x]
5208 +3*cr+2)*cr+d-1] > 1)))
5211 if (d && state->kblocks) {
5212 if (check_killer_cage_sum(
5213 state->kblocks, state->kgrid, state->grid,
5214 state->kblocks->whichblock[y*cr+x]) == 0)
5218 draw_number(dr, ds, state, x, y, highlight);
5223 * Update the _entire_ grid if necessary.
5226 draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
5231 static float game_anim_length(const game_state *oldstate,
5232 const game_state *newstate, int dir, game_ui *ui)
5237 static float game_flash_length(const game_state *oldstate,
5238 const game_state *newstate, int dir, game_ui *ui)
5240 if (!oldstate->completed && newstate->completed &&
5241 !oldstate->cheated && !newstate->cheated)
5246 static int game_status(const game_state *state)
5248 return state->completed ? +1 : 0;
5251 static int game_timing_state(const game_state *state, game_ui *ui)
5253 if (state->completed)
5258 static void game_print_size(const game_params *params, float *x, float *y)
5263 * I'll use 9mm squares by default. They should be quite big
5264 * for this game, because players will want to jot down no end
5265 * of pencil marks in the squares.
5267 game_compute_size(params, 900, &pw, &ph);
5273 * Subfunction to draw the thick lines between cells. In order to do
5274 * this using the line-drawing rather than rectangle-drawing API (so
5275 * as to get line thicknesses to scale correctly) and yet have
5276 * correctly mitred joins between lines, we must do this by tracing
5277 * the boundary of each sub-block and drawing it in one go as a
5280 * This subfunction is also reused with thinner dotted lines to
5281 * outline the Killer cages, this time offsetting the outline toward
5282 * the interior of the affected squares.
5284 static void outline_block_structure(drawing *dr, game_drawstate *ds,
5285 const game_state *state,
5286 struct block_structure *blocks,
5292 int x, y, dx, dy, sx, sy, sdx, sdy;
5295 * Maximum perimeter of a k-omino is 2k+2. (Proof: start
5296 * with k unconnected squares, with total perimeter 4k.
5297 * Now repeatedly join two disconnected components
5298 * together into a larger one; every time you do so you
5299 * remove at least two unit edges, and you require k-1 of
5300 * these operations to create a single connected piece, so
5301 * you must have at most 4k-2(k-1) = 2k+2 unit edges left
5304 coords = snewn(4*cr+4, int); /* 2k+2 points, 2 coords per point */
5307 * Iterate over all the blocks.
5309 for (bi = 0; bi < blocks->nr_blocks; bi++) {
5310 if (blocks->nr_squares[bi] == 0)
5314 * For each block, find a starting square within it
5315 * which has a boundary at the left.
5317 for (i = 0; i < cr; i++) {
5318 int j = blocks->blocks[bi][i];
5319 if (j % cr == 0 || blocks->whichblock[j-1] != bi)
5322 assert(i < cr); /* every block must have _some_ leftmost square */
5323 x = blocks->blocks[bi][i] % cr;
5324 y = blocks->blocks[bi][i] / cr;
5329 * Now begin tracing round the perimeter. At all
5330 * times, (x,y) describes some square within the
5331 * block, and (x+dx,y+dy) is some adjacent square
5332 * outside it; so the edge between those two squares
5333 * is always an edge of the block.
5335 sx = x, sy = y, sdx = dx, sdy = dy; /* save starting position */
5338 int cx, cy, tx, ty, nin;
5341 * Advance to the next edge, by looking at the two
5342 * squares beyond it. If they're both outside the block,
5343 * we turn right (by leaving x,y the same and rotating
5344 * dx,dy clockwise); if they're both inside, we turn
5345 * left (by rotating dx,dy anticlockwise and contriving
5346 * to leave x+dx,y+dy unchanged); if one of each, we go
5347 * straight on (and may enforce by assertion that
5348 * they're one of each the _right_ way round).
5353 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
5354 blocks->whichblock[ty*cr+tx] == bi);
5357 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
5358 blocks->whichblock[ty*cr+tx] == bi);
5367 } else if (nin == 2) {
5391 * Now enforce by assertion that we ended up
5392 * somewhere sensible.
5394 assert(x >= 0 && x < cr && y >= 0 && y < cr &&
5395 blocks->whichblock[y*cr+x] == bi);
5396 assert(x+dx < 0 || x+dx >= cr || y+dy < 0 || y+dy >= cr ||
5397 blocks->whichblock[(y+dy)*cr+(x+dx)] != bi);
5400 * Record the point we just went past at one end of the
5401 * edge. To do this, we translate (x,y) down and right
5402 * by half a unit (so they're describing a point in the
5403 * _centre_ of the square) and then translate back again
5404 * in a manner rotated by dy and dx.
5407 cx = ((2*x+1) + dy + dx) / 2;
5408 cy = ((2*y+1) - dx + dy) / 2;
5409 coords[2*n+0] = BORDER + cx * TILE_SIZE;
5410 coords[2*n+1] = BORDER + cy * TILE_SIZE;
5411 coords[2*n+0] -= dx * inset;
5412 coords[2*n+1] -= dy * inset;
5415 * We turned right, so inset this corner back along
5416 * the edge towards the centre of the square.
5418 coords[2*n+0] -= dy * inset;
5419 coords[2*n+1] += dx * inset;
5420 } else if (nin == 2) {
5422 * We turned left, so inset this corner further
5423 * _out_ along the edge into the next square.
5425 coords[2*n+0] += dy * inset;
5426 coords[2*n+1] -= dx * inset;
5430 } while (x != sx || y != sy || dx != sdx || dy != sdy);
5433 * That's our polygon; now draw it.
5435 draw_polygon(dr, coords, n, -1, ink);
5441 static void game_print(drawing *dr, const game_state *state, int tilesize)
5444 int ink = print_mono_colour(dr, 0);
5447 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
5448 game_drawstate ads, *ds = &ads;
5449 game_set_size(dr, ds, NULL, tilesize);
5454 print_line_width(dr, 3 * TILE_SIZE / 40);
5455 draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
5458 * Highlight X-diagonal squares.
5462 int xhighlight = print_grey_colour(dr, 0.90F);
5464 for (i = 0; i < cr; i++)
5465 draw_rect(dr, BORDER + i*TILE_SIZE, BORDER + i*TILE_SIZE,
5466 TILE_SIZE, TILE_SIZE, xhighlight);
5467 for (i = 0; i < cr; i++)
5468 if (i*2 != cr-1) /* avoid redoing centre square, just for fun */
5469 draw_rect(dr, BORDER + i*TILE_SIZE,
5470 BORDER + (cr-1-i)*TILE_SIZE,
5471 TILE_SIZE, TILE_SIZE, xhighlight);
5477 for (x = 1; x < cr; x++) {
5478 print_line_width(dr, TILE_SIZE / 40);
5479 draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
5480 BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
5482 for (y = 1; y < cr; y++) {
5483 print_line_width(dr, TILE_SIZE / 40);
5484 draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
5485 BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
5489 * Thick lines between cells.
5491 print_line_width(dr, 3 * TILE_SIZE / 40);
5492 outline_block_structure(dr, ds, state, state->blocks, ink, 0);
5495 * Killer cages and their totals.
5497 if (state->kblocks) {
5498 print_line_width(dr, TILE_SIZE / 40);
5499 print_line_dotted(dr, TRUE);
5500 outline_block_structure(dr, ds, state, state->kblocks, ink,
5501 5 * TILE_SIZE / 40);
5502 print_line_dotted(dr, FALSE);
5503 for (y = 0; y < cr; y++)
5504 for (x = 0; x < cr; x++)
5505 if (state->kgrid[y*cr+x]) {
5507 sprintf(str, "%d", state->kgrid[y*cr+x]);
5509 BORDER+x*TILE_SIZE + 7*TILE_SIZE/40,
5510 BORDER+y*TILE_SIZE + 16*TILE_SIZE/40,
5511 FONT_VARIABLE, TILE_SIZE/4,
5512 ALIGN_VNORMAL | ALIGN_HLEFT,
5518 * Standard (non-Killer) clue numbers.
5520 for (y = 0; y < cr; y++)
5521 for (x = 0; x < cr; x++)
5522 if (state->grid[y*cr+x]) {
5525 str[0] = state->grid[y*cr+x] + '0';
5527 str[0] += 'a' - ('9'+1);
5528 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
5529 BORDER + y*TILE_SIZE + TILE_SIZE/2,
5530 FONT_VARIABLE, TILE_SIZE/2,
5531 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
5536 #define thegame solo
5539 const struct game thegame = {
5540 "Solo", "games.solo", "solo",
5542 game_fetch_preset, NULL,
5547 TRUE, game_configure, custom_params,
5555 TRUE, game_can_format_as_text_now, game_text_format,
5563 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
5566 game_free_drawstate,
5571 TRUE, FALSE, game_print_size, game_print,
5572 FALSE, /* wants_statusbar */
5573 FALSE, game_timing_state,
5574 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
5577 #ifdef STANDALONE_SOLVER
5579 int main(int argc, char **argv)
5583 char *id = NULL, *desc;
5586 struct difficulty dlev;
5588 while (--argc > 0) {
5590 if (!strcmp(p, "-v")) {
5591 solver_show_working = TRUE;
5592 } else if (!strcmp(p, "-g")) {
5594 } else if (*p == '-') {
5595 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
5603 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
5607 desc = strchr(id, ':');
5609 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
5614 p = default_params();
5615 decode_params(p, id);
5616 err = validate_desc(p, desc);
5618 fprintf(stderr, "%s: %s\n", argv[0], err);
5621 s = new_game(NULL, p, desc);
5623 dlev.maxdiff = DIFF_RECURSIVE;
5624 dlev.maxkdiff = DIFF_KINTERSECT;
5625 solver(s->cr, s->blocks, s->kblocks, s->xtype, s->grid, s->kgrid, &dlev);
5627 printf("Difficulty rating: %s\n",
5628 dlev.diff==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
5629 dlev.diff==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
5630 dlev.diff==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
5631 dlev.diff==DIFF_SET ? "Advanced (set elimination required)":
5632 dlev.diff==DIFF_EXTREME ? "Extreme (complex non-recursive techniques required)":
5633 dlev.diff==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
5634 dlev.diff==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
5635 dlev.diff==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
5636 "INTERNAL ERROR: unrecognised difficulty code");
5638 printf("Killer difficulty: %s\n",
5639 dlev.kdiff==DIFF_KSINGLE ? "Trivial (single square cages only)":
5640 dlev.kdiff==DIFF_KMINMAX ? "Simple (maximum sum analysis required)":
5641 dlev.kdiff==DIFF_KSUMS ? "Intermediate (sum possibilities)":
5642 dlev.kdiff==DIFF_KINTERSECT ? "Advanced (sum region intersections)":
5643 "INTERNAL ERROR: unrecognised difficulty code");
5645 printf("%s\n", grid_text_format(s->cr, s->blocks, s->xtype, s->grid));
5653 /* vim: set shiftwidth=4 tabstop=8: */