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(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)
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(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(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].sval = dupstr(buf);
451 ret[1].name = "Rows of sub-blocks";
452 ret[1].type = C_STRING;
453 sprintf(buf, "%d", params->r);
454 ret[1].sval = dupstr(buf);
457 ret[2].name = "\"X\" (require every number in each main diagonal)";
458 ret[2].type = C_BOOLEAN;
460 ret[2].ival = params->xtype;
462 ret[3].name = "Jigsaw (irregularly shaped sub-blocks)";
463 ret[3].type = C_BOOLEAN;
465 ret[3].ival = (params->r == 1);
467 ret[4].name = "Killer (digit sums)";
468 ret[4].type = C_BOOLEAN;
470 ret[4].ival = params->killer;
472 ret[5].name = "Symmetry";
473 ret[5].type = C_CHOICES;
474 ret[5].sval = ":None:2-way rotation:4-way rotation:2-way mirror:"
475 "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
477 ret[5].ival = params->symm;
479 ret[6].name = "Difficulty";
480 ret[6].type = C_CHOICES;
481 ret[6].sval = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
482 ret[6].ival = params->diff;
492 static game_params *custom_params(config_item *cfg)
494 game_params *ret = snew(game_params);
496 ret->c = atoi(cfg[0].sval);
497 ret->r = atoi(cfg[1].sval);
498 ret->xtype = cfg[2].ival;
503 ret->killer = cfg[4].ival;
504 ret->symm = cfg[5].ival;
505 ret->diff = cfg[6].ival;
506 ret->kdiff = DIFF_KINTERSECT;
511 static char *validate_params(game_params *params, int full)
514 return "Both dimensions must be at least 2";
515 if (params->c > ORDER_MAX || params->r > ORDER_MAX)
516 return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
517 if ((params->c * params->r) > 31)
518 return "Unable to support more than 31 distinct symbols in a puzzle";
519 if (params->killer && params->c * params->r > 9)
520 return "Killer puzzle dimensions must be smaller than 10.";
525 * ----------------------------------------------------------------------
526 * Block structure functions.
529 static struct block_structure *alloc_block_structure(int c, int r, int area,
534 struct block_structure *b = snew(struct block_structure);
537 b->nr_blocks = nr_blocks;
538 b->max_nr_squares = max_nr_squares;
539 b->c = c; b->r = r; b->area = area;
540 b->whichblock = snewn(area, int);
541 b->blocks_data = snewn(nr_blocks * max_nr_squares, int);
542 b->blocks = snewn(nr_blocks, int *);
543 b->nr_squares = snewn(nr_blocks, int);
545 for (i = 0; i < nr_blocks; i++)
546 b->blocks[i] = b->blocks_data + i*max_nr_squares;
548 #ifdef STANDALONE_SOLVER
549 b->blocknames = (char **)smalloc(c*r*(sizeof(char *)+80));
550 for (i = 0; i < c * r; i++)
551 b->blocknames[i] = NULL;
556 static void free_block_structure(struct block_structure *b)
558 if (--b->refcount == 0) {
559 sfree(b->whichblock);
561 sfree(b->blocks_data);
562 #ifdef STANDALONE_SOLVER
563 sfree(b->blocknames);
565 sfree(b->nr_squares);
570 static struct block_structure *dup_block_structure(struct block_structure *b)
572 struct block_structure *nb;
575 nb = alloc_block_structure(b->c, b->r, b->area, b->max_nr_squares,
577 memcpy(nb->nr_squares, b->nr_squares, b->nr_blocks * sizeof *b->nr_squares);
578 memcpy(nb->whichblock, b->whichblock, b->area * sizeof *b->whichblock);
579 memcpy(nb->blocks_data, b->blocks_data,
580 b->nr_blocks * b->max_nr_squares * sizeof *b->blocks_data);
581 for (i = 0; i < b->nr_blocks; i++)
582 nb->blocks[i] = nb->blocks_data + i*nb->max_nr_squares;
584 #ifdef STANDALONE_SOLVER
585 nb->blocknames = (char **)smalloc(b->c * b->r *(sizeof(char *)+80));
586 memcpy(nb->blocknames, b->blocknames, b->c * b->r *(sizeof(char *)+80));
589 for (i = 0; i < b->c * b->r; i++)
590 if (b->blocknames[i] == NULL)
591 nb->blocknames[i] = NULL;
593 nb->blocknames[i] = ((char *)nb->blocknames) + (b->blocknames[i] - (char *)b->blocknames);
599 static void split_block(struct block_structure *b, int *squares, int nr_squares)
602 int previous_block = b->whichblock[squares[0]];
603 int newblock = b->nr_blocks;
605 assert(b->max_nr_squares >= nr_squares);
606 assert(b->nr_squares[previous_block] > nr_squares);
609 b->blocks_data = sresize(b->blocks_data,
610 b->nr_blocks * b->max_nr_squares, int);
611 b->nr_squares = sresize(b->nr_squares, b->nr_blocks, int);
613 b->blocks = snewn(b->nr_blocks, int *);
614 for (i = 0; i < b->nr_blocks; i++)
615 b->blocks[i] = b->blocks_data + i*b->max_nr_squares;
616 for (i = 0; i < nr_squares; i++) {
617 assert(b->whichblock[squares[i]] == previous_block);
618 b->whichblock[squares[i]] = newblock;
619 b->blocks[newblock][i] = squares[i];
621 for (i = j = 0; i < b->nr_squares[previous_block]; i++) {
623 int sq = b->blocks[previous_block][i];
624 for (k = 0; k < nr_squares; k++)
625 if (squares[k] == sq)
628 b->blocks[previous_block][j++] = sq;
630 b->nr_squares[previous_block] -= nr_squares;
631 b->nr_squares[newblock] = nr_squares;
634 static void remove_from_block(struct block_structure *blocks, int b, int n)
637 blocks->whichblock[n] = -1;
638 for (i = j = 0; i < blocks->nr_squares[b]; i++)
639 if (blocks->blocks[b][i] != n)
640 blocks->blocks[b][j++] = blocks->blocks[b][i];
642 blocks->nr_squares[b]--;
645 /* ----------------------------------------------------------------------
648 * This solver is used for two purposes:
649 * + to check solubility of a grid as we gradually remove numbers
651 * + to solve an externally generated puzzle when the user selects
654 * It supports a variety of specific modes of reasoning. By
655 * enabling or disabling subsets of these modes we can arrange a
656 * range of difficulty levels.
660 * Modes of reasoning currently supported:
662 * - Positional elimination: a number must go in a particular
663 * square because all the other empty squares in a given
664 * row/col/blk are ruled out.
666 * - Killer minmax elimination: for killer-type puzzles, a number
667 * is impossible if choosing it would cause the sum in a killer
668 * region to be guaranteed to be too large or too small.
670 * - Numeric elimination: a square must have a particular number
671 * in because all the other numbers that could go in it are
674 * - Intersectional analysis: given two domains which overlap
675 * (hence one must be a block, and the other can be a row or
676 * col), if the possible locations for a particular number in
677 * one of the domains can be narrowed down to the overlap, then
678 * that number can be ruled out everywhere but the overlap in
679 * the other domain too.
681 * - Set elimination: if there is a subset of the empty squares
682 * within a domain such that the union of the possible numbers
683 * in that subset has the same size as the subset itself, then
684 * those numbers can be ruled out everywhere else in the domain.
685 * (For example, if there are five empty squares and the
686 * possible numbers in each are 12, 23, 13, 134 and 1345, then
687 * the first three empty squares form such a subset: the numbers
688 * 1, 2 and 3 _must_ be in those three squares in some
689 * permutation, and hence we can deduce none of them can be in
690 * the fourth or fifth squares.)
691 * + You can also see this the other way round, concentrating
692 * on numbers rather than squares: if there is a subset of
693 * the unplaced numbers within a domain such that the union
694 * of all their possible positions has the same size as the
695 * subset itself, then all other numbers can be ruled out for
696 * those positions. However, it turns out that this is
697 * exactly equivalent to the first formulation at all times:
698 * there is a 1-1 correspondence between suitable subsets of
699 * the unplaced numbers and suitable subsets of the unfilled
700 * places, found by taking the _complement_ of the union of
701 * the numbers' possible positions (or the spaces' possible
704 * - Forcing chains (see comment for solver_forcing().)
706 * - Recursion. If all else fails, we pick one of the currently
707 * most constrained empty squares and take a random guess at its
708 * contents, then continue solving on that basis and see if we
712 struct solver_usage {
714 struct block_structure *blocks, *kblocks, *extra_cages;
716 * We set up a cubic array, indexed by x, y and digit; each
717 * element of this array is TRUE or FALSE according to whether
718 * or not that digit _could_ in principle go in that position.
720 * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
721 * are macros below to help with this.
725 * This is the grid in which we write down our final
726 * deductions. y-coordinates in here are _not_ transformed.
730 * For killer-type puzzles, kclues holds the secondary clue for
731 * each cage. For derived cages, the clue is in extra_clues.
733 digit *kclues, *extra_clues;
735 * Now we keep track, at a slightly higher level, of what we
736 * have yet to work out, to prevent doing the same deduction
739 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
741 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
743 /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
745 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
746 unsigned char *diag; /* diag 0 is \, 1 is / */
752 #define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
753 #define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
754 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
755 #define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
757 #define ondiag0(xy) ((xy) % (cr+1) == 0)
758 #define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
759 #define diag0(i) ((i) * (cr+1))
760 #define diag1(i) ((i+1) * (cr-1))
763 * Function called when we are certain that a particular square has
764 * a particular number in it. The y-coordinate passed in here is
767 static void solver_place(struct solver_usage *usage, int x, int y, int n)
770 int sqindex = y*cr+x;
776 * Rule out all other numbers in this square.
778 for (i = 1; i <= cr; i++)
783 * Rule out this number in all other positions in the row.
785 for (i = 0; i < cr; i++)
790 * Rule out this number in all other positions in the column.
792 for (i = 0; i < cr; i++)
797 * Rule out this number in all other positions in the block.
799 bi = usage->blocks->whichblock[sqindex];
800 for (i = 0; i < cr; i++) {
801 int bp = usage->blocks->blocks[bi][i];
807 * Enter the number in the result grid.
809 usage->grid[sqindex] = n;
812 * Cross out this number from the list of numbers left to place
813 * in its row, its column and its block.
815 usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
816 usage->blk[bi*cr+n-1] = TRUE;
819 if (ondiag0(sqindex)) {
820 for (i = 0; i < cr; i++)
821 if (diag0(i) != sqindex)
822 cube2(diag0(i),n) = FALSE;
823 usage->diag[n-1] = TRUE;
825 if (ondiag1(sqindex)) {
826 for (i = 0; i < cr; i++)
827 if (diag1(i) != sqindex)
828 cube2(diag1(i),n) = FALSE;
829 usage->diag[cr+n-1] = TRUE;
834 static int solver_elim(struct solver_usage *usage, int *indices
835 #ifdef STANDALONE_SOLVER
844 * Count the number of set bits within this section of the
849 for (i = 0; i < cr; i++)
850 if (usage->cube[indices[i]]) {
864 if (!usage->grid[y*cr+x]) {
865 #ifdef STANDALONE_SOLVER
866 if (solver_show_working) {
868 printf("%*s", solver_recurse_depth*4, "");
872 printf(":\n%*s placing %d at (%d,%d)\n",
873 solver_recurse_depth*4, "", n, 1+x, 1+y);
876 solver_place(usage, x, y, n);
880 #ifdef STANDALONE_SOLVER
881 if (solver_show_working) {
883 printf("%*s", solver_recurse_depth*4, "");
887 printf(":\n%*s no possibilities available\n",
888 solver_recurse_depth*4, "");
897 static int solver_intersect(struct solver_usage *usage,
898 int *indices1, int *indices2
899 #ifdef STANDALONE_SOLVER
908 * Loop over the first domain and see if there's any set bit
909 * not also in the second.
911 for (i = j = 0; i < cr; i++) {
913 while (j < cr && indices2[j] < p)
915 if (usage->cube[p]) {
916 if (j < cr && indices2[j] == p)
917 continue; /* both domains contain this index */
919 return 0; /* there is, so we can't deduce */
924 * We have determined that all set bits in the first domain are
925 * within its overlap with the second. So loop over the second
926 * domain and remove all set bits that aren't also in that
927 * overlap; return +1 iff we actually _did_ anything.
930 for (i = j = 0; i < cr; i++) {
932 while (j < cr && indices1[j] < p)
934 if (usage->cube[p] && (j >= cr || indices1[j] != p)) {
935 #ifdef STANDALONE_SOLVER
936 if (solver_show_working) {
941 printf("%*s", solver_recurse_depth*4, "");
953 printf("%*s ruling out %d at (%d,%d)\n",
954 solver_recurse_depth*4, "", pn, 1+px, 1+py);
957 ret = +1; /* we did something */
965 struct solver_scratch {
966 unsigned char *grid, *rowidx, *colidx, *set;
967 int *neighbours, *bfsqueue;
968 int *indexlist, *indexlist2;
969 #ifdef STANDALONE_SOLVER
974 static int solver_set(struct solver_usage *usage,
975 struct solver_scratch *scratch,
977 #ifdef STANDALONE_SOLVER
984 unsigned char *grid = scratch->grid;
985 unsigned char *rowidx = scratch->rowidx;
986 unsigned char *colidx = scratch->colidx;
987 unsigned char *set = scratch->set;
990 * We are passed a cr-by-cr matrix of booleans. Our first job
991 * is to winnow it by finding any definite placements - i.e.
992 * any row with a solitary 1 - and discarding that row and the
993 * column containing the 1.
995 memset(rowidx, TRUE, cr);
996 memset(colidx, TRUE, cr);
997 for (i = 0; i < cr; i++) {
998 int count = 0, first = -1;
999 for (j = 0; j < cr; j++)
1000 if (usage->cube[indices[i*cr+j]])
1004 * If count == 0, then there's a row with no 1s at all and
1005 * the puzzle is internally inconsistent. However, we ought
1006 * to have caught this already during the simpler reasoning
1007 * methods, so we can safely fail an assertion if we reach
1012 rowidx[i] = colidx[first] = FALSE;
1016 * Convert each of rowidx/colidx from a list of 0s and 1s to a
1017 * list of the indices of the 1s.
1019 for (i = j = 0; i < cr; i++)
1023 for (i = j = 0; i < cr; i++)
1029 * And create the smaller matrix.
1031 for (i = 0; i < n; i++)
1032 for (j = 0; j < n; j++)
1033 grid[i*cr+j] = usage->cube[indices[rowidx[i]*cr+colidx[j]]];
1036 * Having done that, we now have a matrix in which every row
1037 * has at least two 1s in. Now we search to see if we can find
1038 * a rectangle of zeroes (in the set-theoretic sense of
1039 * `rectangle', i.e. a subset of rows crossed with a subset of
1040 * columns) whose width and height add up to n.
1047 * We have a candidate set. If its size is <=1 or >=n-1
1048 * then we move on immediately.
1050 if (count > 1 && count < n-1) {
1052 * The number of rows we need is n-count. See if we can
1053 * find that many rows which each have a zero in all
1054 * the positions listed in `set'.
1057 for (i = 0; i < n; i++) {
1059 for (j = 0; j < n; j++)
1060 if (set[j] && grid[i*cr+j]) {
1069 * We expect never to be able to get _more_ than
1070 * n-count suitable rows: this would imply that (for
1071 * example) there are four numbers which between them
1072 * have at most three possible positions, and hence it
1073 * indicates a faulty deduction before this point or
1074 * even a bogus clue.
1076 if (rows > n - count) {
1077 #ifdef STANDALONE_SOLVER
1078 if (solver_show_working) {
1080 printf("%*s", solver_recurse_depth*4,
1085 printf(":\n%*s contradiction reached\n",
1086 solver_recurse_depth*4, "");
1092 if (rows >= n - count) {
1093 int progress = FALSE;
1096 * We've got one! Now, for each row which _doesn't_
1097 * satisfy the criterion, eliminate all its set
1098 * bits in the positions _not_ listed in `set'.
1099 * Return +1 (meaning progress has been made) if we
1100 * successfully eliminated anything at all.
1102 * This involves referring back through
1103 * rowidx/colidx in order to work out which actual
1104 * positions in the cube to meddle with.
1106 for (i = 0; i < n; i++) {
1108 for (j = 0; j < n; j++)
1109 if (set[j] && grid[i*cr+j]) {
1114 for (j = 0; j < n; j++)
1115 if (!set[j] && grid[i*cr+j]) {
1116 int fpos = indices[rowidx[i]*cr+colidx[j]];
1117 #ifdef STANDALONE_SOLVER
1118 if (solver_show_working) {
1123 printf("%*s", solver_recurse_depth*4,
1136 printf("%*s ruling out %d at (%d,%d)\n",
1137 solver_recurse_depth*4, "",
1142 usage->cube[fpos] = FALSE;
1154 * Binary increment: change the rightmost 0 to a 1, and
1155 * change all 1s to the right of it to 0s.
1158 while (i > 0 && set[i-1])
1159 set[--i] = 0, count--;
1161 set[--i] = 1, count++;
1170 * Look for forcing chains. A forcing chain is a path of
1171 * pairwise-exclusive squares (i.e. each pair of adjacent squares
1172 * in the path are in the same row, column or block) with the
1173 * following properties:
1175 * (a) Each square on the path has precisely two possible numbers.
1177 * (b) Each pair of squares which are adjacent on the path share
1178 * at least one possible number in common.
1180 * (c) Each square in the middle of the path shares _both_ of its
1181 * numbers with at least one of its neighbours (not the same
1182 * one with both neighbours).
1184 * These together imply that at least one of the possible number
1185 * choices at one end of the path forces _all_ the rest of the
1186 * numbers along the path. In order to make real use of this, we
1187 * need further properties:
1189 * (c) Ruling out some number N from the square at one end of the
1190 * path forces the square at the other end to take the same
1193 * (d) The two end squares are both in line with some third
1196 * (e) That third square currently has N as a possibility.
1198 * If we can find all of that lot, we can deduce that at least one
1199 * of the two ends of the forcing chain has number N, and that
1200 * therefore the mutually adjacent third square does not.
1202 * To find forcing chains, we're going to start a bfs at each
1203 * suitable square, once for each of its two possible numbers.
1205 static int solver_forcing(struct solver_usage *usage,
1206 struct solver_scratch *scratch)
1209 int *bfsqueue = scratch->bfsqueue;
1210 #ifdef STANDALONE_SOLVER
1211 int *bfsprev = scratch->bfsprev;
1213 unsigned char *number = scratch->grid;
1214 int *neighbours = scratch->neighbours;
1217 for (y = 0; y < cr; y++)
1218 for (x = 0; x < cr; x++) {
1222 * If this square doesn't have exactly two candidate
1223 * numbers, don't try it.
1225 * In this loop we also sum the candidate numbers,
1226 * which is a nasty hack to allow us to quickly find
1227 * `the other one' (since we will shortly know there
1230 for (count = t = 0, n = 1; n <= cr; n++)
1237 * Now attempt a bfs for each candidate.
1239 for (n = 1; n <= cr; n++)
1240 if (cube(x, y, n)) {
1241 int orign, currn, head, tail;
1248 memset(number, cr+1, cr*cr);
1250 bfsqueue[tail++] = y*cr+x;
1251 #ifdef STANDALONE_SOLVER
1252 bfsprev[y*cr+x] = -1;
1254 number[y*cr+x] = t - n;
1256 while (head < tail) {
1257 int xx, yy, nneighbours, xt, yt, i;
1259 xx = bfsqueue[head++];
1263 currn = number[yy*cr+xx];
1266 * Find neighbours of yy,xx.
1269 for (yt = 0; yt < cr; yt++)
1270 neighbours[nneighbours++] = yt*cr+xx;
1271 for (xt = 0; xt < cr; xt++)
1272 neighbours[nneighbours++] = yy*cr+xt;
1273 xt = usage->blocks->whichblock[yy*cr+xx];
1274 for (yt = 0; yt < cr; yt++)
1275 neighbours[nneighbours++] = usage->blocks->blocks[xt][yt];
1277 int sqindex = yy*cr+xx;
1278 if (ondiag0(sqindex)) {
1279 for (i = 0; i < cr; i++)
1280 neighbours[nneighbours++] = diag0(i);
1282 if (ondiag1(sqindex)) {
1283 for (i = 0; i < cr; i++)
1284 neighbours[nneighbours++] = diag1(i);
1289 * Try visiting each of those neighbours.
1291 for (i = 0; i < nneighbours; i++) {
1294 xt = neighbours[i] % cr;
1295 yt = neighbours[i] / cr;
1298 * We need this square to not be
1299 * already visited, and to include
1300 * currn as a possible number.
1302 if (number[yt*cr+xt] <= cr)
1304 if (!cube(xt, yt, currn))
1308 * Don't visit _this_ square a second
1311 if (xt == xx && yt == yy)
1315 * To continue with the bfs, we need
1316 * this square to have exactly two
1319 for (cc = tt = 0, nn = 1; nn <= cr; nn++)
1320 if (cube(xt, yt, nn))
1323 bfsqueue[tail++] = yt*cr+xt;
1324 #ifdef STANDALONE_SOLVER
1325 bfsprev[yt*cr+xt] = yy*cr+xx;
1327 number[yt*cr+xt] = tt - currn;
1331 * One other possibility is that this
1332 * might be the square in which we can
1333 * make a real deduction: if it's
1334 * adjacent to x,y, and currn is equal
1335 * to the original number we ruled out.
1337 if (currn == orign &&
1338 (xt == x || yt == y ||
1339 (usage->blocks->whichblock[yt*cr+xt] == usage->blocks->whichblock[y*cr+x]) ||
1340 (usage->diag && ((ondiag0(yt*cr+xt) && ondiag0(y*cr+x)) ||
1341 (ondiag1(yt*cr+xt) && ondiag1(y*cr+x)))))) {
1342 #ifdef STANDALONE_SOLVER
1343 if (solver_show_working) {
1346 printf("%*sforcing chain, %d at ends of ",
1347 solver_recurse_depth*4, "", orign);
1351 printf("%s(%d,%d)", sep, 1+xl,
1353 xl = bfsprev[yl*cr+xl];
1360 printf("\n%*s ruling out %d at (%d,%d)\n",
1361 solver_recurse_depth*4, "",
1365 cube(xt, yt, orign) = FALSE;
1376 static int solver_killer_minmax(struct solver_usage *usage,
1377 struct block_structure *cages, digit *clues,
1379 #ifdef STANDALONE_SOLVER
1387 int nsquares = cages->nr_squares[b];
1392 for (i = 0; i < nsquares; i++) {
1393 int n, x = cages->blocks[b][i];
1395 for (n = 1; n <= cr; n++)
1397 int maxval = 0, minval = 0;
1399 for (j = 0; j < nsquares; j++) {
1401 int y = cages->blocks[b][j];
1404 for (m = 1; m <= cr; m++)
1409 for (m = cr; m > 0; m--)
1415 if (maxval + n < clues[b]) {
1416 cube2(x, n) = FALSE;
1418 #ifdef STANDALONE_SOLVER
1419 if (solver_show_working)
1420 printf("%*s ruling out %d at (%d,%d) as too low %s\n",
1421 solver_recurse_depth*4, "killer minmax analysis",
1422 n, 1 + x%cr, 1 + x/cr, extra);
1425 if (minval + n > clues[b]) {
1426 cube2(x, n) = FALSE;
1428 #ifdef STANDALONE_SOLVER
1429 if (solver_show_working)
1430 printf("%*s ruling out %d at (%d,%d) as too high %s\n",
1431 solver_recurse_depth*4, "killer minmax analysis",
1432 n, 1 + x%cr, 1 + x/cr, extra);
1440 static int solver_killer_sums(struct solver_usage *usage, int b,
1441 struct block_structure *cages, int clue,
1443 #ifdef STANDALONE_SOLVER
1444 , const char *cage_type
1449 int i, ret, max_sums;
1450 int nsquares = cages->nr_squares[b];
1451 unsigned long *sumbits, possible_addends;
1454 assert(nsquares == 0);
1457 assert(nsquares > 0);
1462 if (!cage_is_region) {
1463 int known_row = -1, known_col = -1, known_block = -1;
1465 * Verify that the cage lies entirely within one region,
1466 * so that using the precomputed sums is valid.
1468 for (i = 0; i < nsquares; i++) {
1469 int x = cages->blocks[b][i];
1471 assert(usage->grid[x] == 0);
1476 known_block = usage->blocks->whichblock[x];
1478 if (known_row != x/cr)
1480 if (known_col != x%cr)
1482 if (known_block != usage->blocks->whichblock[x])
1486 if (known_block == -1 && known_col == -1 && known_row == -1)
1489 if (nsquares == 2) {
1490 if (clue < 3 || clue > 17)
1493 sumbits = sum_bits2[clue];
1494 max_sums = MAX_2SUMS;
1495 } else if (nsquares == 3) {
1496 if (clue < 6 || clue > 24)
1499 sumbits = sum_bits3[clue];
1500 max_sums = MAX_3SUMS;
1502 if (clue < 10 || clue > 30)
1505 sumbits = sum_bits4[clue];
1506 max_sums = MAX_4SUMS;
1509 * For every possible way to get the sum, see if there is
1510 * one square in the cage that disallows all the required
1511 * addends. If we find one such square, this way to compute
1512 * the sum is impossible.
1514 possible_addends = 0;
1515 for (i = 0; i < max_sums; i++) {
1517 unsigned long bits = sumbits[i];
1522 for (j = 0; j < nsquares; j++) {
1524 unsigned long square_bits = bits;
1525 int x = cages->blocks[b][j];
1526 for (n = 1; n <= cr; n++)
1528 square_bits &= ~(1L << n);
1529 if (square_bits == 0) {
1534 possible_addends |= bits;
1537 * Now we know which addends can possibly be used to
1538 * compute the sum. Remove all other digits from the
1539 * set of possibilities.
1541 if (possible_addends == 0)
1545 for (i = 0; i < nsquares; i++) {
1547 int x = cages->blocks[b][i];
1548 for (n = 1; n <= cr; n++) {
1551 if ((possible_addends & (1 << n)) == 0) {
1552 cube2(x, n) = FALSE;
1554 #ifdef STANDALONE_SOLVER
1555 if (solver_show_working) {
1556 printf("%*s using %s\n",
1557 solver_recurse_depth*4, "killer sums analysis",
1559 printf("%*s ruling out %d at (%d,%d) due to impossible %d-sum\n",
1560 solver_recurse_depth*4, "",
1561 n, 1 + x%cr, 1 + x/cr, nsquares);
1570 static int filter_whole_cages(struct solver_usage *usage, int *squares, int n,
1576 /* First, filter squares with a clue. */
1577 for (i = j = 0; i < n; i++)
1578 if (usage->grid[squares[i]])
1579 *filtered_sum += usage->grid[squares[i]];
1581 squares[j++] = squares[i];
1585 * Filter all cages that are covered entirely by the list of
1589 for (b = 0; b < usage->kblocks->nr_blocks && off < n; b++) {
1590 int b_squares = usage->kblocks->nr_squares[b];
1597 * Find all squares of block b that lie in our list,
1598 * and make them contiguous at off, which is the current position
1599 * in the output list.
1601 for (i = 0; i < b_squares; i++) {
1602 for (j = off; j < n; j++)
1603 if (squares[j] == usage->kblocks->blocks[b][i]) {
1604 int t = squares[off + matched];
1605 squares[off + matched] = squares[j];
1611 /* If so, filter out all squares of b from the list. */
1612 if (matched != usage->kblocks->nr_squares[b]) {
1616 memmove(squares + off, squares + off + matched,
1617 (n - off - matched) * sizeof *squares);
1620 *filtered_sum += usage->kclues[b];
1626 static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
1628 struct solver_scratch *scratch = snew(struct solver_scratch);
1630 scratch->grid = snewn(cr*cr, unsigned char);
1631 scratch->rowidx = snewn(cr, unsigned char);
1632 scratch->colidx = snewn(cr, unsigned char);
1633 scratch->set = snewn(cr, unsigned char);
1634 scratch->neighbours = snewn(5*cr, int);
1635 scratch->bfsqueue = snewn(cr*cr, int);
1636 #ifdef STANDALONE_SOLVER
1637 scratch->bfsprev = snewn(cr*cr, int);
1639 scratch->indexlist = snewn(cr*cr, int); /* used for set elimination */
1640 scratch->indexlist2 = snewn(cr, int); /* only used for intersect() */
1644 static void solver_free_scratch(struct solver_scratch *scratch)
1646 #ifdef STANDALONE_SOLVER
1647 sfree(scratch->bfsprev);
1649 sfree(scratch->bfsqueue);
1650 sfree(scratch->neighbours);
1651 sfree(scratch->set);
1652 sfree(scratch->colidx);
1653 sfree(scratch->rowidx);
1654 sfree(scratch->grid);
1655 sfree(scratch->indexlist);
1656 sfree(scratch->indexlist2);
1661 * Used for passing information about difficulty levels between the solver
1665 /* Maximum levels allowed. */
1666 int maxdiff, maxkdiff;
1667 /* Levels reached by the solver. */
1671 static void solver(int cr, struct block_structure *blocks,
1672 struct block_structure *kblocks, int xtype,
1673 digit *grid, digit *kgrid, struct difficulty *dlev)
1675 struct solver_usage *usage;
1676 struct solver_scratch *scratch;
1677 int x, y, b, i, n, ret;
1678 int diff = DIFF_BLOCK;
1679 int kdiff = DIFF_KSINGLE;
1682 * Set up a usage structure as a clean slate (everything
1685 usage = snew(struct solver_usage);
1687 usage->blocks = blocks;
1689 usage->kblocks = dup_block_structure(kblocks);
1690 usage->extra_cages = alloc_block_structure (kblocks->c, kblocks->r,
1691 cr * cr, cr, cr * cr);
1692 usage->extra_clues = snewn(cr*cr, digit);
1694 usage->kblocks = usage->extra_cages = NULL;
1695 usage->extra_clues = NULL;
1697 usage->cube = snewn(cr*cr*cr, unsigned char);
1698 usage->grid = grid; /* write straight back to the input */
1700 int nclues = kblocks->nr_blocks;
1702 * Allow for expansion of the killer regions, the absolute
1703 * limit is obviously one region per square.
1705 usage->kclues = snewn(cr*cr, digit);
1706 for (i = 0; i < nclues; i++) {
1707 for (n = 0; n < kblocks->nr_squares[i]; n++)
1708 if (kgrid[kblocks->blocks[i][n]] != 0)
1709 usage->kclues[i] = kgrid[kblocks->blocks[i][n]];
1710 assert(usage->kclues[i] > 0);
1712 memset(usage->kclues + nclues, 0, cr*cr - nclues);
1714 usage->kclues = NULL;
1717 memset(usage->cube, TRUE, cr*cr*cr);
1719 usage->row = snewn(cr * cr, unsigned char);
1720 usage->col = snewn(cr * cr, unsigned char);
1721 usage->blk = snewn(cr * cr, unsigned char);
1722 memset(usage->row, FALSE, cr * cr);
1723 memset(usage->col, FALSE, cr * cr);
1724 memset(usage->blk, FALSE, cr * cr);
1727 usage->diag = snewn(cr * 2, unsigned char);
1728 memset(usage->diag, FALSE, cr * 2);
1732 usage->nr_regions = cr * 3 + (xtype ? 2 : 0);
1733 usage->regions = snewn(cr * usage->nr_regions, int);
1734 usage->sq2region = snewn(cr * cr * 3, int *);
1736 for (n = 0; n < cr; n++) {
1737 for (i = 0; i < cr; i++) {
1740 b = usage->blocks->blocks[n][i];
1741 usage->regions[cr*n*3 + i] = x;
1742 usage->regions[cr*n*3 + cr + i] = y;
1743 usage->regions[cr*n*3 + 2*cr + i] = b;
1744 usage->sq2region[x*3] = usage->regions + cr*n*3;
1745 usage->sq2region[y*3 + 1] = usage->regions + cr*n*3 + cr;
1746 usage->sq2region[b*3 + 2] = usage->regions + cr*n*3 + 2*cr;
1750 scratch = solver_new_scratch(usage);
1753 * Place all the clue numbers we are given.
1755 for (x = 0; x < cr; x++)
1756 for (y = 0; y < cr; y++)
1758 solver_place(usage, x, y, grid[y*cr+x]);
1761 * Now loop over the grid repeatedly trying all permitted modes
1762 * of reasoning. The loop terminates if we complete an
1763 * iteration without making any progress; we then return
1764 * failure or success depending on whether the grid is full or
1769 * I'd like to write `continue;' inside each of the
1770 * following loops, so that the solver returns here after
1771 * making some progress. However, I can't specify that I
1772 * want to continue an outer loop rather than the innermost
1773 * one, so I'm apologetically resorting to a goto.
1778 * Blockwise positional elimination.
1780 for (b = 0; b < cr; b++)
1781 for (n = 1; n <= cr; n++)
1782 if (!usage->blk[b*cr+n-1]) {
1783 for (i = 0; i < cr; i++)
1784 scratch->indexlist[i] = cubepos2(usage->blocks->blocks[b][i],n);
1785 ret = solver_elim(usage, scratch->indexlist
1786 #ifdef STANDALONE_SOLVER
1787 , "positional elimination,"
1788 " %d in block %s", n,
1789 usage->blocks->blocknames[b]
1793 diff = DIFF_IMPOSSIBLE;
1795 } else if (ret > 0) {
1796 diff = max(diff, DIFF_BLOCK);
1801 if (usage->kclues != NULL) {
1802 int changed = FALSE;
1805 * First, bring the kblocks into a more useful form: remove
1806 * all filled-in squares, and reduce the sum by their values.
1807 * Walk in reverse order, since otherwise remove_from_block
1808 * can move element past our loop counter.
1810 for (b = 0; b < usage->kblocks->nr_blocks; b++)
1811 for (i = usage->kblocks->nr_squares[b] -1; i >= 0; i--) {
1812 int x = usage->kblocks->blocks[b][i];
1813 int t = usage->grid[x];
1817 remove_from_block(usage->kblocks, b, x);
1818 if (t > usage->kclues[b]) {
1819 diff = DIFF_IMPOSSIBLE;
1822 usage->kclues[b] -= t;
1824 * Since cages are regions, this tells us something
1825 * about the other squares in the cage.
1827 for (n = 0; n < usage->kblocks->nr_squares[b]; n++) {
1828 cube2(usage->kblocks->blocks[b][n], t) = FALSE;
1833 * The most trivial kind of solver for killer puzzles: fill
1834 * single-square cages.
1836 for (b = 0; b < usage->kblocks->nr_blocks; b++) {
1837 int squares = usage->kblocks->nr_squares[b];
1839 int v = usage->kclues[b];
1840 if (v < 1 || v > cr) {
1841 diff = DIFF_IMPOSSIBLE;
1844 x = usage->kblocks->blocks[b][0] % cr;
1845 y = usage->kblocks->blocks[b][0] / cr;
1846 if (!cube(x, y, v)) {
1847 diff = DIFF_IMPOSSIBLE;
1850 solver_place(usage, x, y, v);
1852 #ifdef STANDALONE_SOLVER
1853 if (solver_show_working) {
1854 printf("%*s placing %d at (%d,%d)\n",
1855 solver_recurse_depth*4, "killer single-square cage",
1856 v, 1 + x%cr, 1 + x/cr);
1864 kdiff = max(kdiff, DIFF_KSINGLE);
1868 if (dlev->maxkdiff >= DIFF_KINTERSECT && usage->kclues != NULL) {
1869 int changed = FALSE;
1871 * Now, create the extra_cages information. Every full region
1872 * (row, column, or block) has the same sum total (45 for 3x3
1873 * puzzles. After we try to cover these regions with cages that
1874 * lie entirely within them, any squares that remain must bring
1875 * the total to this known value, and so they form additional
1876 * cages which aren't immediately evident in the displayed form
1879 usage->extra_cages->nr_blocks = 0;
1880 for (i = 0; i < 3; i++) {
1881 for (n = 0; n < cr; n++) {
1882 int *region = usage->regions + cr*n*3 + i*cr;
1883 int sum = cr * (cr + 1) / 2;
1886 int n_extra = usage->extra_cages->nr_blocks;
1887 int *extra_list = usage->extra_cages->blocks[n_extra];
1888 memcpy(extra_list, region, cr * sizeof *extra_list);
1890 nsquares = filter_whole_cages(usage, extra_list, nsquares, &filtered);
1892 if (nsquares == cr || nsquares == 0)
1894 if (dlev->maxdiff >= DIFF_RECURSIVE) {
1896 dlev->diff = DIFF_IMPOSSIBLE;
1902 if (nsquares == 1) {
1904 diff = DIFF_IMPOSSIBLE;
1907 x = extra_list[0] % cr;
1908 y = extra_list[0] / cr;
1909 if (!cube(x, y, sum)) {
1910 diff = DIFF_IMPOSSIBLE;
1913 solver_place(usage, x, y, sum);
1915 #ifdef STANDALONE_SOLVER
1916 if (solver_show_working) {
1917 printf("%*s placing %d at (%d,%d)\n",
1918 solver_recurse_depth*4, "killer single-square deduced cage",
1924 b = usage->kblocks->whichblock[extra_list[0]];
1925 for (x = 1; x < nsquares; x++)
1926 if (usage->kblocks->whichblock[extra_list[x]] != b)
1928 if (x == nsquares) {
1929 assert(usage->kblocks->nr_squares[b] > nsquares);
1930 split_block(usage->kblocks, extra_list, nsquares);
1931 assert(usage->kblocks->nr_squares[usage->kblocks->nr_blocks - 1] == nsquares);
1932 usage->kclues[usage->kblocks->nr_blocks - 1] = sum;
1933 usage->kclues[b] -= sum;
1935 usage->extra_cages->nr_squares[n_extra] = nsquares;
1936 usage->extra_cages->nr_blocks++;
1937 usage->extra_clues[n_extra] = sum;
1942 kdiff = max(kdiff, DIFF_KINTERSECT);
1948 * Another simple killer-type elimination. For every square in a
1949 * cage, find the minimum and maximum possible sums of all the
1950 * other squares in the same cage, and rule out possibilities
1951 * for the given square based on whether they are guaranteed to
1952 * cause the sum to be either too high or too low.
1953 * This is a special case of trying all possible sums across a
1954 * region, which is a recursive algorithm. We should probably
1955 * implement it for a higher difficulty level.
1957 if (dlev->maxkdiff >= DIFF_KMINMAX && usage->kclues != NULL) {
1958 int changed = FALSE;
1959 for (b = 0; b < usage->kblocks->nr_blocks; b++) {
1960 int ret = solver_killer_minmax(usage, usage->kblocks,
1962 #ifdef STANDALONE_SOLVER
1967 diff = DIFF_IMPOSSIBLE;
1972 for (b = 0; b < usage->extra_cages->nr_blocks; b++) {
1973 int ret = solver_killer_minmax(usage, usage->extra_cages,
1974 usage->extra_clues, b
1975 #ifdef STANDALONE_SOLVER
1976 , "using deduced cages"
1980 diff = DIFF_IMPOSSIBLE;
1986 kdiff = max(kdiff, DIFF_KMINMAX);
1992 * Try to use knowledge of which numbers can be used to generate
1994 * This can only be used if a cage lies entirely within a region.
1996 if (dlev->maxkdiff >= DIFF_KSUMS && usage->kclues != NULL) {
1997 int changed = FALSE;
1999 for (b = 0; b < usage->kblocks->nr_blocks; b++) {
2000 int ret = solver_killer_sums(usage, b, usage->kblocks,
2001 usage->kclues[b], TRUE
2002 #ifdef STANDALONE_SOLVER
2008 kdiff = max(kdiff, DIFF_KSUMS);
2009 } else if (ret < 0) {
2010 diff = DIFF_IMPOSSIBLE;
2015 for (b = 0; b < usage->extra_cages->nr_blocks; b++) {
2016 int ret = solver_killer_sums(usage, b, usage->extra_cages,
2017 usage->extra_clues[b], FALSE
2018 #ifdef STANDALONE_SOLVER
2024 kdiff = max(kdiff, DIFF_KINTERSECT);
2025 } else if (ret < 0) {
2026 diff = DIFF_IMPOSSIBLE;
2035 if (dlev->maxdiff <= DIFF_BLOCK)
2039 * Row-wise positional elimination.
2041 for (y = 0; y < cr; y++)
2042 for (n = 1; n <= cr; n++)
2043 if (!usage->row[y*cr+n-1]) {
2044 for (x = 0; x < cr; x++)
2045 scratch->indexlist[x] = cubepos(x, y, n);
2046 ret = solver_elim(usage, scratch->indexlist
2047 #ifdef STANDALONE_SOLVER
2048 , "positional elimination,"
2049 " %d in row %d", n, 1+y
2053 diff = DIFF_IMPOSSIBLE;
2055 } else if (ret > 0) {
2056 diff = max(diff, DIFF_SIMPLE);
2061 * Column-wise positional elimination.
2063 for (x = 0; x < cr; x++)
2064 for (n = 1; n <= cr; n++)
2065 if (!usage->col[x*cr+n-1]) {
2066 for (y = 0; y < cr; y++)
2067 scratch->indexlist[y] = cubepos(x, y, n);
2068 ret = solver_elim(usage, scratch->indexlist
2069 #ifdef STANDALONE_SOLVER
2070 , "positional elimination,"
2071 " %d in column %d", n, 1+x
2075 diff = DIFF_IMPOSSIBLE;
2077 } else if (ret > 0) {
2078 diff = max(diff, DIFF_SIMPLE);
2084 * X-diagonal positional elimination.
2087 for (n = 1; n <= cr; n++)
2088 if (!usage->diag[n-1]) {
2089 for (i = 0; i < cr; i++)
2090 scratch->indexlist[i] = cubepos2(diag0(i), n);
2091 ret = solver_elim(usage, scratch->indexlist
2092 #ifdef STANDALONE_SOLVER
2093 , "positional elimination,"
2094 " %d in \\-diagonal", n
2098 diff = DIFF_IMPOSSIBLE;
2100 } else if (ret > 0) {
2101 diff = max(diff, DIFF_SIMPLE);
2105 for (n = 1; n <= cr; n++)
2106 if (!usage->diag[cr+n-1]) {
2107 for (i = 0; i < cr; i++)
2108 scratch->indexlist[i] = cubepos2(diag1(i), n);
2109 ret = solver_elim(usage, scratch->indexlist
2110 #ifdef STANDALONE_SOLVER
2111 , "positional elimination,"
2112 " %d in /-diagonal", n
2116 diff = DIFF_IMPOSSIBLE;
2118 } else if (ret > 0) {
2119 diff = max(diff, DIFF_SIMPLE);
2126 * Numeric elimination.
2128 for (x = 0; x < cr; x++)
2129 for (y = 0; y < cr; y++)
2130 if (!usage->grid[y*cr+x]) {
2131 for (n = 1; n <= cr; n++)
2132 scratch->indexlist[n-1] = cubepos(x, y, n);
2133 ret = solver_elim(usage, scratch->indexlist
2134 #ifdef STANDALONE_SOLVER
2135 , "numeric elimination at (%d,%d)",
2140 diff = DIFF_IMPOSSIBLE;
2142 } else if (ret > 0) {
2143 diff = max(diff, DIFF_SIMPLE);
2148 if (dlev->maxdiff <= DIFF_SIMPLE)
2152 * Intersectional analysis, rows vs blocks.
2154 for (y = 0; y < cr; y++)
2155 for (b = 0; b < cr; b++)
2156 for (n = 1; n <= cr; n++) {
2157 if (usage->row[y*cr+n-1] ||
2158 usage->blk[b*cr+n-1])
2160 for (i = 0; i < cr; i++) {
2161 scratch->indexlist[i] = cubepos(i, y, n);
2162 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2165 * solver_intersect() never returns -1.
2167 if (solver_intersect(usage, scratch->indexlist,
2169 #ifdef STANDALONE_SOLVER
2170 , "intersectional analysis,"
2171 " %d in row %d vs block %s",
2172 n, 1+y, usage->blocks->blocknames[b]
2175 solver_intersect(usage, scratch->indexlist2,
2177 #ifdef STANDALONE_SOLVER
2178 , "intersectional analysis,"
2179 " %d in block %s vs row %d",
2180 n, usage->blocks->blocknames[b], 1+y
2183 diff = max(diff, DIFF_INTERSECT);
2189 * Intersectional analysis, columns vs blocks.
2191 for (x = 0; x < cr; x++)
2192 for (b = 0; b < cr; b++)
2193 for (n = 1; n <= cr; n++) {
2194 if (usage->col[x*cr+n-1] ||
2195 usage->blk[b*cr+n-1])
2197 for (i = 0; i < cr; i++) {
2198 scratch->indexlist[i] = cubepos(x, i, n);
2199 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2201 if (solver_intersect(usage, scratch->indexlist,
2203 #ifdef STANDALONE_SOLVER
2204 , "intersectional analysis,"
2205 " %d in column %d vs block %s",
2206 n, 1+x, usage->blocks->blocknames[b]
2209 solver_intersect(usage, scratch->indexlist2,
2211 #ifdef STANDALONE_SOLVER
2212 , "intersectional analysis,"
2213 " %d in block %s vs column %d",
2214 n, usage->blocks->blocknames[b], 1+x
2217 diff = max(diff, DIFF_INTERSECT);
2224 * Intersectional analysis, \-diagonal vs blocks.
2226 for (b = 0; b < cr; b++)
2227 for (n = 1; n <= cr; n++) {
2228 if (usage->diag[n-1] ||
2229 usage->blk[b*cr+n-1])
2231 for (i = 0; i < cr; i++) {
2232 scratch->indexlist[i] = cubepos2(diag0(i), n);
2233 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2235 if (solver_intersect(usage, scratch->indexlist,
2237 #ifdef STANDALONE_SOLVER
2238 , "intersectional analysis,"
2239 " %d in \\-diagonal vs block %s",
2240 n, 1+x, usage->blocks->blocknames[b]
2243 solver_intersect(usage, scratch->indexlist2,
2245 #ifdef STANDALONE_SOLVER
2246 , "intersectional analysis,"
2247 " %d in block %s vs \\-diagonal",
2248 n, usage->blocks->blocknames[b], 1+x
2251 diff = max(diff, DIFF_INTERSECT);
2257 * Intersectional analysis, /-diagonal vs blocks.
2259 for (b = 0; b < cr; b++)
2260 for (n = 1; n <= cr; n++) {
2261 if (usage->diag[cr+n-1] ||
2262 usage->blk[b*cr+n-1])
2264 for (i = 0; i < cr; i++) {
2265 scratch->indexlist[i] = cubepos2(diag1(i), n);
2266 scratch->indexlist2[i] = cubepos2(usage->blocks->blocks[b][i], n);
2268 if (solver_intersect(usage, scratch->indexlist,
2270 #ifdef STANDALONE_SOLVER
2271 , "intersectional analysis,"
2272 " %d in /-diagonal vs block %s",
2273 n, 1+x, usage->blocks->blocknames[b]
2276 solver_intersect(usage, scratch->indexlist2,
2278 #ifdef STANDALONE_SOLVER
2279 , "intersectional analysis,"
2280 " %d in block %s vs /-diagonal",
2281 n, usage->blocks->blocknames[b], 1+x
2284 diff = max(diff, DIFF_INTERSECT);
2290 if (dlev->maxdiff <= DIFF_INTERSECT)
2294 * Blockwise set elimination.
2296 for (b = 0; b < cr; b++) {
2297 for (i = 0; i < cr; i++)
2298 for (n = 1; n <= cr; n++)
2299 scratch->indexlist[i*cr+n-1] = cubepos2(usage->blocks->blocks[b][i], n);
2300 ret = solver_set(usage, scratch, scratch->indexlist
2301 #ifdef STANDALONE_SOLVER
2302 , "set elimination, block %s",
2303 usage->blocks->blocknames[b]
2307 diff = DIFF_IMPOSSIBLE;
2309 } else if (ret > 0) {
2310 diff = max(diff, DIFF_SET);
2316 * Row-wise set elimination.
2318 for (y = 0; y < cr; y++) {
2319 for (x = 0; x < cr; x++)
2320 for (n = 1; n <= cr; n++)
2321 scratch->indexlist[x*cr+n-1] = cubepos(x, y, n);
2322 ret = solver_set(usage, scratch, scratch->indexlist
2323 #ifdef STANDALONE_SOLVER
2324 , "set elimination, row %d", 1+y
2328 diff = DIFF_IMPOSSIBLE;
2330 } else if (ret > 0) {
2331 diff = max(diff, DIFF_SET);
2337 * Column-wise set elimination.
2339 for (x = 0; x < cr; x++) {
2340 for (y = 0; y < cr; y++)
2341 for (n = 1; n <= cr; n++)
2342 scratch->indexlist[y*cr+n-1] = cubepos(x, y, n);
2343 ret = solver_set(usage, scratch, scratch->indexlist
2344 #ifdef STANDALONE_SOLVER
2345 , "set elimination, column %d", 1+x
2349 diff = DIFF_IMPOSSIBLE;
2351 } else if (ret > 0) {
2352 diff = max(diff, DIFF_SET);
2359 * \-diagonal set elimination.
2361 for (i = 0; i < cr; i++)
2362 for (n = 1; n <= cr; n++)
2363 scratch->indexlist[i*cr+n-1] = cubepos2(diag0(i), n);
2364 ret = solver_set(usage, scratch, scratch->indexlist
2365 #ifdef STANDALONE_SOLVER
2366 , "set elimination, \\-diagonal"
2370 diff = DIFF_IMPOSSIBLE;
2372 } else if (ret > 0) {
2373 diff = max(diff, DIFF_SET);
2378 * /-diagonal set elimination.
2380 for (i = 0; i < cr; i++)
2381 for (n = 1; n <= cr; n++)
2382 scratch->indexlist[i*cr+n-1] = cubepos2(diag1(i), n);
2383 ret = solver_set(usage, scratch, scratch->indexlist
2384 #ifdef STANDALONE_SOLVER
2385 , "set elimination, \\-diagonal"
2389 diff = DIFF_IMPOSSIBLE;
2391 } else if (ret > 0) {
2392 diff = max(diff, DIFF_SET);
2397 if (dlev->maxdiff <= DIFF_SET)
2401 * Row-vs-column set elimination on a single number.
2403 for (n = 1; n <= cr; n++) {
2404 for (y = 0; y < cr; y++)
2405 for (x = 0; x < cr; x++)
2406 scratch->indexlist[y*cr+x] = cubepos(x, y, n);
2407 ret = solver_set(usage, scratch, scratch->indexlist
2408 #ifdef STANDALONE_SOLVER
2409 , "positional set elimination, number %d", n
2413 diff = DIFF_IMPOSSIBLE;
2415 } else if (ret > 0) {
2416 diff = max(diff, DIFF_EXTREME);
2424 if (solver_forcing(usage, scratch)) {
2425 diff = max(diff, DIFF_EXTREME);
2430 * If we reach here, we have made no deductions in this
2431 * iteration, so the algorithm terminates.
2437 * Last chance: if we haven't fully solved the puzzle yet, try
2438 * recursing based on guesses for a particular square. We pick
2439 * one of the most constrained empty squares we can find, which
2440 * has the effect of pruning the search tree as much as
2443 if (dlev->maxdiff >= DIFF_RECURSIVE) {
2444 int best, bestcount;
2449 for (y = 0; y < cr; y++)
2450 for (x = 0; x < cr; x++)
2451 if (!grid[y*cr+x]) {
2455 * An unfilled square. Count the number of
2456 * possible digits in it.
2459 for (n = 1; n <= cr; n++)
2464 * We should have found any impossibilities
2465 * already, so this can safely be an assert.
2469 if (count < bestcount) {
2477 digit *list, *ingrid, *outgrid;
2479 diff = DIFF_IMPOSSIBLE; /* no solution found yet */
2482 * Attempt recursion.
2487 list = snewn(cr, digit);
2488 ingrid = snewn(cr * cr, digit);
2489 outgrid = snewn(cr * cr, digit);
2490 memcpy(ingrid, grid, cr * cr);
2492 /* Make a list of the possible digits. */
2493 for (j = 0, n = 1; n <= cr; n++)
2497 #ifdef STANDALONE_SOLVER
2498 if (solver_show_working) {
2500 printf("%*srecursing on (%d,%d) [",
2501 solver_recurse_depth*4, "", x + 1, y + 1);
2502 for (i = 0; i < j; i++) {
2503 printf("%s%d", sep, list[i]);
2511 * And step along the list, recursing back into the
2512 * main solver at every stage.
2514 for (i = 0; i < j; i++) {
2515 memcpy(outgrid, ingrid, cr * cr);
2516 outgrid[y*cr+x] = list[i];
2518 #ifdef STANDALONE_SOLVER
2519 if (solver_show_working)
2520 printf("%*sguessing %d at (%d,%d)\n",
2521 solver_recurse_depth*4, "", list[i], x + 1, y + 1);
2522 solver_recurse_depth++;
2525 solver(cr, blocks, kblocks, xtype, outgrid, kgrid, dlev);
2527 #ifdef STANDALONE_SOLVER
2528 solver_recurse_depth--;
2529 if (solver_show_working) {
2530 printf("%*sretracting %d at (%d,%d)\n",
2531 solver_recurse_depth*4, "", list[i], x + 1, y + 1);
2536 * If we have our first solution, copy it into the
2537 * grid we will return.
2539 if (diff == DIFF_IMPOSSIBLE && dlev->diff != DIFF_IMPOSSIBLE)
2540 memcpy(grid, outgrid, cr*cr);
2542 if (dlev->diff == DIFF_AMBIGUOUS)
2543 diff = DIFF_AMBIGUOUS;
2544 else if (dlev->diff == DIFF_IMPOSSIBLE)
2545 /* do not change our return value */;
2547 /* the recursion turned up exactly one solution */
2548 if (diff == DIFF_IMPOSSIBLE)
2549 diff = DIFF_RECURSIVE;
2551 diff = DIFF_AMBIGUOUS;
2555 * As soon as we've found more than one solution,
2556 * give up immediately.
2558 if (diff == DIFF_AMBIGUOUS)
2569 * We're forbidden to use recursion, so we just see whether
2570 * our grid is fully solved, and return DIFF_IMPOSSIBLE
2573 for (y = 0; y < cr; y++)
2574 for (x = 0; x < cr; x++)
2576 diff = DIFF_IMPOSSIBLE;
2581 dlev->kdiff = kdiff;
2583 #ifdef STANDALONE_SOLVER
2584 if (solver_show_working)
2585 printf("%*s%s found\n",
2586 solver_recurse_depth*4, "",
2587 diff == DIFF_IMPOSSIBLE ? "no solution" :
2588 diff == DIFF_AMBIGUOUS ? "multiple solutions" :
2596 if (usage->kblocks) {
2597 free_block_structure(usage->kblocks);
2598 free_block_structure(usage->extra_cages);
2599 sfree(usage->extra_clues);
2603 solver_free_scratch(scratch);
2606 /* ----------------------------------------------------------------------
2607 * End of solver code.
2610 /* ----------------------------------------------------------------------
2611 * Killer set generator.
2614 /* ----------------------------------------------------------------------
2615 * Solo filled-grid generator.
2617 * This grid generator works by essentially trying to solve a grid
2618 * starting from no clues, and not worrying that there's more than
2619 * one possible solution. Unfortunately, it isn't computationally
2620 * feasible to do this by calling the above solver with an empty
2621 * grid, because that one needs to allocate a lot of scratch space
2622 * at every recursion level. Instead, I have a much simpler
2623 * algorithm which I shamelessly copied from a Python solver
2624 * written by Andrew Wilkinson (which is GPLed, but I've reused
2625 * only ideas and no code). It mostly just does the obvious
2626 * recursive thing: pick an empty square, put one of the possible
2627 * digits in it, recurse until all squares are filled, backtrack
2628 * and change some choices if necessary.
2630 * The clever bit is that every time it chooses which square to
2631 * fill in next, it does so by counting the number of _possible_
2632 * numbers that can go in each square, and it prioritises so that
2633 * it picks a square with the _lowest_ number of possibilities. The
2634 * idea is that filling in lots of the obvious bits (particularly
2635 * any squares with only one possibility) will cut down on the list
2636 * of possibilities for other squares and hence reduce the enormous
2637 * search space as much as possible as early as possible.
2639 * The use of bit sets implies that we support puzzles up to a size of
2640 * 32x32 (less if anyone finds a 16-bit machine to compile this on).
2644 * Internal data structure used in gridgen to keep track of
2647 struct gridgen_coord { int x, y, r; };
2648 struct gridgen_usage {
2650 struct block_structure *blocks, *kblocks;
2651 /* grid is a copy of the input grid, modified as we go along */
2654 * Bitsets. In each of them, bit n is set if digit n has been placed
2655 * in the corresponding region. row, col and blk are used for all
2656 * puzzles. cge is used only for killer puzzles, and diag is used
2657 * only for x-type puzzles.
2658 * All of these have cr entries, except diag which only has 2,
2659 * and cge, which has as many entries as kblocks.
2661 unsigned int *row, *col, *blk, *cge, *diag;
2662 /* This lists all the empty spaces remaining in the grid. */
2663 struct gridgen_coord *spaces;
2665 /* If we need randomisation in the solve, this is our random state. */
2669 static void gridgen_place(struct gridgen_usage *usage, int x, int y, digit n)
2671 unsigned int bit = 1 << n;
2673 usage->row[y] |= bit;
2674 usage->col[x] |= bit;
2675 usage->blk[usage->blocks->whichblock[y*cr+x]] |= bit;
2677 usage->cge[usage->kblocks->whichblock[y*cr+x]] |= bit;
2679 if (ondiag0(y*cr+x))
2680 usage->diag[0] |= bit;
2681 if (ondiag1(y*cr+x))
2682 usage->diag[1] |= bit;
2684 usage->grid[y*cr+x] = n;
2687 static void gridgen_remove(struct gridgen_usage *usage, int x, int y, digit n)
2689 unsigned int mask = ~(1 << n);
2691 usage->row[y] &= mask;
2692 usage->col[x] &= mask;
2693 usage->blk[usage->blocks->whichblock[y*cr+x]] &= mask;
2695 usage->cge[usage->kblocks->whichblock[y*cr+x]] &= mask;
2697 if (ondiag0(y*cr+x))
2698 usage->diag[0] &= mask;
2699 if (ondiag1(y*cr+x))
2700 usage->diag[1] &= mask;
2702 usage->grid[y*cr+x] = 0;
2708 * The real recursive step in the generating function.
2710 * Return values: 1 means solution found, 0 means no solution
2711 * found on this branch.
2713 static int gridgen_real(struct gridgen_usage *usage, digit *grid, int *steps)
2716 int i, j, n, sx, sy, bestm, bestr, ret;
2721 * Firstly, check for completion! If there are no spaces left
2722 * in the grid, we have a solution.
2724 if (usage->nspaces == 0)
2728 * Next, abandon generation if we went over our steps limit.
2735 * Otherwise, there must be at least one space. Find the most
2736 * constrained space, using the `r' field as a tie-breaker.
2738 bestm = cr+1; /* so that any space will beat it */
2742 for (j = 0; j < usage->nspaces; j++) {
2743 int x = usage->spaces[j].x, y = usage->spaces[j].y;
2744 unsigned int used_xy;
2747 m = usage->blocks->whichblock[y*cr+x];
2748 used_xy = usage->row[y] | usage->col[x] | usage->blk[m];
2749 if (usage->cge != NULL)
2750 used_xy |= usage->cge[usage->kblocks->whichblock[y*cr+x]];
2751 if (usage->cge != NULL)
2752 used_xy |= usage->cge[usage->kblocks->whichblock[y*cr+x]];
2753 if (usage->diag != NULL) {
2754 if (ondiag0(y*cr+x))
2755 used_xy |= usage->diag[0];
2756 if (ondiag1(y*cr+x))
2757 used_xy |= usage->diag[1];
2761 * Find the number of digits that could go in this space.
2764 for (n = 1; n <= cr; n++) {
2765 unsigned int bit = 1 << n;
2766 if ((used_xy & bit) == 0)
2769 if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
2771 bestr = usage->spaces[j].r;
2780 * Swap that square into the final place in the spaces array,
2781 * so that decrementing nspaces will remove it from the list.
2783 if (i != usage->nspaces-1) {
2784 struct gridgen_coord t;
2785 t = usage->spaces[usage->nspaces-1];
2786 usage->spaces[usage->nspaces-1] = usage->spaces[i];
2787 usage->spaces[i] = t;
2791 * Now we've decided which square to start our recursion at,
2792 * simply go through all possible values, shuffling them
2793 * randomly first if necessary.
2795 digits = snewn(bestm, int);
2798 for (n = 1; n <= cr; n++) {
2799 unsigned int bit = 1 << n;
2801 if ((used & bit) == 0)
2806 shuffle(digits, j, sizeof(*digits), usage->rs);
2808 /* And finally, go through the digit list and actually recurse. */
2810 for (i = 0; i < j; i++) {
2813 /* Update the usage structure to reflect the placing of this digit. */
2814 gridgen_place(usage, sx, sy, n);
2817 /* Call the solver recursively. Stop when we find a solution. */
2818 if (gridgen_real(usage, grid, steps)) {
2823 /* Revert the usage structure. */
2824 gridgen_remove(usage, sx, sy, n);
2833 * Entry point to generator. You give it parameters and a starting
2834 * grid, which is simply an array of cr*cr digits.
2836 static int gridgen(int cr, struct block_structure *blocks,
2837 struct block_structure *kblocks, int xtype,
2838 digit *grid, random_state *rs, int maxsteps)
2840 struct gridgen_usage *usage;
2844 * Clear the grid to start with.
2846 memset(grid, 0, cr*cr);
2849 * Create a gridgen_usage structure.
2851 usage = snew(struct gridgen_usage);
2854 usage->blocks = blocks;
2858 usage->row = snewn(cr, unsigned int);
2859 usage->col = snewn(cr, unsigned int);
2860 usage->blk = snewn(cr, unsigned int);
2861 if (kblocks != NULL) {
2862 usage->kblocks = kblocks;
2863 usage->cge = snewn(usage->kblocks->nr_blocks, unsigned int);
2864 memset(usage->cge, FALSE, kblocks->nr_blocks * sizeof *usage->cge);
2869 memset(usage->row, 0, cr * sizeof *usage->row);
2870 memset(usage->col, 0, cr * sizeof *usage->col);
2871 memset(usage->blk, 0, cr * sizeof *usage->blk);
2874 usage->diag = snewn(2, unsigned int);
2875 memset(usage->diag, 0, 2 * sizeof *usage->diag);
2881 * Begin by filling in the whole top row with randomly chosen
2882 * numbers. This cannot introduce any bias or restriction on
2883 * the available grids, since we already know those numbers
2884 * are all distinct so all we're doing is choosing their
2887 for (x = 0; x < cr; x++)
2889 shuffle(grid, cr, sizeof(*grid), rs);
2890 for (x = 0; x < cr; x++)
2891 gridgen_place(usage, x, 0, grid[x]);
2893 usage->spaces = snewn(cr * cr, struct gridgen_coord);
2899 * Initialise the list of grid spaces, taking care to leave
2900 * out the row I've already filled in above.
2902 for (y = 1; y < cr; y++) {
2903 for (x = 0; x < cr; x++) {
2904 usage->spaces[usage->nspaces].x = x;
2905 usage->spaces[usage->nspaces].y = y;
2906 usage->spaces[usage->nspaces].r = random_bits(rs, 31);
2912 * Run the real generator function.
2914 ret = gridgen_real(usage, grid, &maxsteps);
2917 * Clean up the usage structure now we have our answer.
2919 sfree(usage->spaces);
2929 /* ----------------------------------------------------------------------
2930 * End of grid generator code.
2934 * Check whether a grid contains a valid complete puzzle.
2936 static int check_valid(int cr, struct block_structure *blocks,
2937 struct block_structure *kblocks, int xtype, digit *grid)
2939 unsigned char *used;
2942 used = snewn(cr, unsigned char);
2945 * Check that each row contains precisely one of everything.
2947 for (y = 0; y < cr; y++) {
2948 memset(used, FALSE, cr);
2949 for (x = 0; x < cr; x++)
2950 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2951 used[grid[y*cr+x]-1] = TRUE;
2952 for (n = 0; n < cr; n++)
2960 * Check that each column contains precisely one of everything.
2962 for (x = 0; x < cr; x++) {
2963 memset(used, FALSE, cr);
2964 for (y = 0; y < cr; y++)
2965 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
2966 used[grid[y*cr+x]-1] = TRUE;
2967 for (n = 0; n < cr; n++)
2975 * Check that each block contains precisely one of everything.
2977 for (i = 0; i < cr; i++) {
2978 memset(used, FALSE, cr);
2979 for (j = 0; j < cr; j++)
2980 if (grid[blocks->blocks[i][j]] > 0 &&
2981 grid[blocks->blocks[i][j]] <= cr)
2982 used[grid[blocks->blocks[i][j]]-1] = TRUE;
2983 for (n = 0; n < cr; n++)
2991 * Check that each Killer cage, if any, contains at most one of
2995 for (i = 0; i < kblocks->nr_blocks; i++) {
2996 memset(used, FALSE, cr);
2997 for (j = 0; j < kblocks->nr_squares[i]; j++)
2998 if (grid[kblocks->blocks[i][j]] > 0 &&
2999 grid[kblocks->blocks[i][j]] <= cr) {
3000 if (used[grid[kblocks->blocks[i][j]]-1]) {
3004 used[grid[kblocks->blocks[i][j]]-1] = TRUE;
3010 * Check that each diagonal contains precisely one of everything.
3013 memset(used, FALSE, cr);
3014 for (i = 0; i < cr; i++)
3015 if (grid[diag0(i)] > 0 && grid[diag0(i)] <= cr)
3016 used[grid[diag0(i)]-1] = TRUE;
3017 for (n = 0; n < cr; n++)
3022 for (i = 0; i < cr; i++)
3023 if (grid[diag1(i)] > 0 && grid[diag1(i)] <= cr)
3024 used[grid[diag1(i)]-1] = TRUE;
3025 for (n = 0; n < cr; n++)
3036 static int symmetries(game_params *params, int x, int y, int *output, int s)
3038 int c = params->c, r = params->r, cr = c*r;
3041 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
3047 break; /* just x,y is all we need */
3049 ADD(cr - 1 - x, cr - 1 - y);
3054 ADD(cr - 1 - x, cr - 1 - y);
3065 ADD(cr - 1 - x, cr - 1 - y);
3069 ADD(cr - 1 - x, cr - 1 - y);
3070 ADD(cr - 1 - y, cr - 1 - x);
3075 ADD(cr - 1 - x, cr - 1 - y);
3079 ADD(cr - 1 - y, cr - 1 - x);
3088 static char *encode_solve_move(int cr, digit *grid)
3091 char *ret, *p, *sep;
3094 * It's surprisingly easy to work out _exactly_ how long this
3095 * string needs to be. To decimal-encode all the numbers from 1
3098 * - every number has a units digit; total is n.
3099 * - all numbers above 9 have a tens digit; total is max(n-9,0).
3100 * - all numbers above 99 have a hundreds digit; total is max(n-99,0).
3104 for (i = 1; i <= cr; i *= 10)
3105 len += max(cr - i + 1, 0);
3106 len += cr; /* don't forget the commas */
3107 len *= cr; /* there are cr rows of these */
3110 * Now len is one bigger than the total size of the
3111 * comma-separated numbers (because we counted an
3112 * additional leading comma). We need to have a leading S
3113 * and a trailing NUL, so we're off by one in total.
3117 ret = snewn(len, char);
3121 for (i = 0; i < cr*cr; i++) {
3122 p += sprintf(p, "%s%d", sep, grid[i]);
3126 assert(p - ret == len);
3131 static void dsf_to_blocks(int *dsf, struct block_structure *blocks,
3132 int min_expected, int max_expected)
3134 int cr = blocks->c * blocks->r, area = cr * cr;
3137 for (i = 0; i < area; i++)
3138 blocks->whichblock[i] = -1;
3139 for (i = 0; i < area; i++) {
3140 int j = dsf_canonify(dsf, i);
3141 if (blocks->whichblock[j] < 0)
3142 blocks->whichblock[j] = nb++;
3143 blocks->whichblock[i] = blocks->whichblock[j];
3145 assert(nb >= min_expected && nb <= max_expected);
3146 blocks->nr_blocks = nb;
3149 static void make_blocks_from_whichblock(struct block_structure *blocks)
3153 for (i = 0; i < blocks->nr_blocks; i++) {
3154 blocks->blocks[i][blocks->max_nr_squares-1] = 0;
3155 blocks->nr_squares[i] = 0;
3157 for (i = 0; i < blocks->area; i++) {
3158 int b = blocks->whichblock[i];
3159 int j = blocks->blocks[b][blocks->max_nr_squares-1]++;
3160 assert(j < blocks->max_nr_squares);
3161 blocks->blocks[b][j] = i;
3162 blocks->nr_squares[b]++;
3166 static char *encode_block_structure_desc(char *p, struct block_structure *blocks)
3169 int c = blocks->c, r = blocks->r, cr = c * r;
3172 * Encode the block structure. We do this by encoding
3173 * the pattern of dividing lines: first we iterate
3174 * over the cr*(cr-1) internal vertical grid lines in
3175 * ordinary reading order, then over the cr*(cr-1)
3176 * internal horizontal ones in transposed reading
3179 * We encode the number of non-lines between the
3180 * lines; _ means zero (two adjacent divisions), a
3181 * means 1, ..., y means 25, and z means 25 non-lines
3182 * _and no following line_ (so that za means 26, zb 27
3185 for (i = 0; i <= 2*cr*(cr-1); i++) {
3186 int x, y, p0, p1, edge;
3188 if (i == 2*cr*(cr-1)) {
3189 edge = TRUE; /* terminating virtual edge */
3191 if (i < cr*(cr-1)) {
3202 edge = (blocks->whichblock[p0] != blocks->whichblock[p1]);
3206 while (currrun > 25)
3207 *p++ = 'z', currrun -= 25;
3209 *p++ = 'a'-1 + currrun;
3219 static char *encode_grid(char *desc, digit *grid, int area)
3225 for (i = 0; i <= area; i++) {
3226 int n = (i < area ? grid[i] : -1);
3233 int c = 'a' - 1 + run;
3237 run -= c - ('a' - 1);
3241 * If there's a number in the very top left or
3242 * bottom right, there's no point putting an
3243 * unnecessary _ before or after it.
3245 if (p > desc && n > 0)
3249 p += sprintf(p, "%d", n);
3257 * Conservatively stimate the number of characters required for
3258 * encoding a grid of a certain area.
3260 static int grid_encode_space (int area)
3263 for (count = 1, t = area; t > 26; t -= 26)
3265 return count * area;
3269 * Conservatively stimate the number of characters required for
3270 * encoding a given blocks structure.
3272 static int blocks_encode_space(struct block_structure *blocks)
3274 int cr = blocks->c * blocks->r, area = cr * cr;
3275 return grid_encode_space(area);
3278 static char *encode_puzzle_desc(game_params *params, digit *grid,
3279 struct block_structure *blocks,
3281 struct block_structure *kblocks)
3283 int c = params->c, r = params->r, cr = c*r;
3288 space = grid_encode_space(area) + 1;
3290 space += blocks_encode_space(blocks) + 1;
3291 if (params->killer) {
3292 space += blocks_encode_space(kblocks) + 1;
3293 space += grid_encode_space(area) + 1;
3295 desc = snewn(space, char);
3296 p = encode_grid(desc, grid, area);
3300 p = encode_block_structure_desc(p, blocks);
3302 if (params->killer) {
3304 p = encode_block_structure_desc(p, kblocks);
3306 p = encode_grid(p, kgrid, area);
3308 assert(p - desc < space);
3310 desc = sresize(desc, p - desc, char);
3315 static void merge_blocks(struct block_structure *b, int n1, int n2)
3318 /* Move data towards the lower block number. */
3325 /* Merge n2 into n1, and move the last block into n2's position. */
3326 for (i = 0; i < b->nr_squares[n2]; i++)
3327 b->whichblock[b->blocks[n2][i]] = n1;
3328 memcpy(b->blocks[n1] + b->nr_squares[n1], b->blocks[n2],
3329 b->nr_squares[n2] * sizeof **b->blocks);
3330 b->nr_squares[n1] += b->nr_squares[n2];
3332 n1 = b->nr_blocks - 1;
3334 memcpy(b->blocks[n2], b->blocks[n1],
3335 b->nr_squares[n1] * sizeof **b->blocks);
3336 for (i = 0; i < b->nr_squares[n1]; i++)
3337 b->whichblock[b->blocks[n1][i]] = n2;
3338 b->nr_squares[n2] = b->nr_squares[n1];
3343 static int merge_some_cages(struct block_structure *b, int cr, int area,
3344 digit *grid, random_state *rs)
3347 * Make a list of all the pairs of adjacent blocks.
3355 pairs = snewn(b->nr_blocks * b->nr_blocks, struct pair);
3358 for (i = 0; i < b->nr_blocks; i++) {
3359 for (j = i+1; j < b->nr_blocks; j++) {
3362 * Rule the merger out of consideration if it's
3363 * obviously not viable.
3365 if (b->nr_squares[i] + b->nr_squares[j] > b->max_nr_squares)
3366 continue; /* we couldn't merge these anyway */
3369 * See if these two blocks have a pair of squares
3370 * adjacent to each other.
3372 for (k = 0; k < b->nr_squares[i]; k++) {
3373 int xy = b->blocks[i][k];
3374 int y = xy / cr, x = xy % cr;
3375 if ((y > 0 && b->whichblock[xy - cr] == j) ||
3376 (y+1 < cr && b->whichblock[xy + cr] == j) ||
3377 (x > 0 && b->whichblock[xy - 1] == j) ||
3378 (x+1 < cr && b->whichblock[xy + 1] == j)) {
3380 * Yes! Add this pair to our list.
3382 pairs[npairs].b1 = i;
3383 pairs[npairs].b2 = j;
3391 * Now go through that list in random order until we find a pair
3392 * of blocks we can merge.
3394 while (npairs > 0) {
3396 unsigned int digits_found;
3399 * Pick a random pair, and remove it from the list.
3401 i = random_upto(rs, npairs);
3405 pairs[i] = pairs[npairs-1];
3408 /* Guarantee that the merged cage would still be a region. */
3410 for (i = 0; i < b->nr_squares[n1]; i++)
3411 digits_found |= 1 << grid[b->blocks[n1][i]];
3412 for (i = 0; i < b->nr_squares[n2]; i++)
3413 if (digits_found & (1 << grid[b->blocks[n2][i]]))
3415 if (i != b->nr_squares[n2])
3419 * Got one! Do the merge.
3421 merge_blocks(b, n1, n2);
3430 static void compute_kclues(struct block_structure *cages, digit *kclues,
3431 digit *grid, int area)
3434 memset(kclues, 0, area * sizeof *kclues);
3435 for (i = 0; i < cages->nr_blocks; i++) {
3437 for (j = 0; j < area; j++)
3438 if (cages->whichblock[j] == i)
3440 for (j = 0; j < area; j++)
3441 if (cages->whichblock[j] == i)
3448 static struct block_structure *gen_killer_cages(int cr, random_state *rs,
3449 int remove_singletons)
3452 int x, y, area = cr * cr;
3453 int n_singletons = 0;
3454 struct block_structure *b = alloc_block_structure (1, cr, area, cr, area);
3456 for (x = 0; x < area; x++)
3457 b->whichblock[x] = -1;
3459 for (y = 0; y < cr; y++)
3460 for (x = 0; x < cr; x++) {
3463 if (b->whichblock[xy] != -1)
3465 b->whichblock[xy] = nr;
3467 rnd = random_bits(rs, 4);
3468 if (xy + 1 < area && (rnd >= 4 || (!remove_singletons && rnd >= 1))) {
3470 if (x + 1 == cr || b->whichblock[xy2] != -1 ||
3471 (xy + cr < area && random_bits(rs, 1) == 0))
3476 b->whichblock[xy2] = nr;
3483 make_blocks_from_whichblock(b);
3485 for (x = y = 0; x < b->nr_blocks; x++)
3486 if (b->nr_squares[x] == 1)
3488 assert(y == n_singletons);
3490 if (n_singletons > 0 && remove_singletons) {
3492 for (n = 0; n < b->nr_blocks;) {
3493 int xy, x, y, xy2, other;
3494 if (b->nr_squares[n] > 1) {
3498 xy = b->blocks[n][0];
3503 else if (x + 1 < cr && (y + 1 == cr || random_bits(rs, 1) == 0))
3507 other = b->whichblock[xy2];
3509 if (b->nr_squares[other] == 1)
3512 merge_blocks(b, n, other);
3516 assert(n_singletons == 0);
3521 static char *new_game_desc(game_params *params, random_state *rs,
3522 char **aux, int interactive)
3524 int c = params->c, r = params->r, cr = c*r;
3526 struct block_structure *blocks, *kblocks;
3527 digit *grid, *grid2, *kgrid;
3528 struct xy { int x, y; } *locs;
3531 int coords[16], ncoords;
3533 struct difficulty dlev;
3535 precompute_sum_bits();
3538 * Adjust the maximum difficulty level to be consistent with
3539 * the puzzle size: all 2x2 puzzles appear to be Trivial
3540 * (DIFF_BLOCK) so we cannot hold out for even a Basic
3541 * (DIFF_SIMPLE) one.
3543 dlev.maxdiff = params->diff;
3544 dlev.maxkdiff = params->kdiff;
3545 if (c == 2 && r == 2)
3546 dlev.maxdiff = DIFF_BLOCK;
3548 grid = snewn(area, digit);
3549 locs = snewn(area, struct xy);
3550 grid2 = snewn(area, digit);
3552 blocks = alloc_block_structure (c, r, area, cr, cr);
3554 if (params->killer) {
3555 kblocks = alloc_block_structure (c, r, area, cr, area);
3556 kgrid = snewn(area, digit);
3562 #ifdef STANDALONE_SOLVER
3563 assert(!"This should never happen, so we don't need to create blocknames");
3567 * Loop until we get a grid of the required difficulty. This is
3568 * nasty, but it seems to be unpleasantly hard to generate
3569 * difficult grids otherwise.
3573 * Generate a random solved state, starting by
3574 * constructing the block structure.
3576 if (r == 1) { /* jigsaw mode */
3577 int *dsf = divvy_rectangle(cr, cr, cr, rs);
3579 dsf_to_blocks (dsf, blocks, cr, cr);
3582 } else { /* basic Sudoku mode */
3583 for (y = 0; y < cr; y++)
3584 for (x = 0; x < cr; x++)
3585 blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
3587 make_blocks_from_whichblock(blocks);
3589 if (params->killer) {
3590 kblocks = gen_killer_cages(cr, rs, params->kdiff > DIFF_KSINGLE);
3593 if (!gridgen(cr, blocks, kblocks, params->xtype, grid, rs, area*area))
3595 assert(check_valid(cr, blocks, kblocks, params->xtype, grid));
3598 * Save the solved grid in aux.
3602 * We might already have written *aux the last time we
3603 * went round this loop, in which case we should free
3604 * the old aux before overwriting it with the new one.
3610 *aux = encode_solve_move(cr, grid);
3614 * Now we have a solved grid. For normal puzzles, we start removing
3615 * things from it while preserving solubility. Killer puzzles are
3616 * different: we just pass the empty grid to the solver, and use
3617 * the puzzle if it comes back solved.
3620 if (params->killer) {
3621 struct block_structure *good_cages = NULL;
3622 struct block_structure *last_cages = NULL;
3625 memcpy(grid2, grid, area);
3628 compute_kclues(kblocks, kgrid, grid2, area);
3630 memset(grid, 0, area * sizeof *grid);
3631 solver(cr, blocks, kblocks, params->xtype, grid, kgrid, &dlev);
3632 if (dlev.diff == dlev.maxdiff && dlev.kdiff == dlev.maxkdiff) {
3634 * We have one that matches our difficulty. Store it for
3635 * later, but keep going.
3638 free_block_structure(good_cages);
3640 good_cages = dup_block_structure(kblocks);
3641 if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3643 } else if (dlev.diff > dlev.maxdiff || dlev.kdiff > dlev.maxkdiff) {
3645 * Give up after too many tries and either use the good one we
3646 * found, or generate a new grid.
3651 * The difficulty level got too high. If we have a good
3652 * one, use it, otherwise go back to the last one that
3653 * was at a lower difficulty and restart the process from
3656 if (good_cages != NULL) {
3657 free_block_structure(kblocks);
3658 kblocks = dup_block_structure(good_cages);
3659 if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3662 if (last_cages == NULL)
3664 free_block_structure(kblocks);
3665 kblocks = last_cages;
3670 free_block_structure(last_cages);
3671 last_cages = dup_block_structure(kblocks);
3672 if (!merge_some_cages(kblocks, cr, area, grid2, rs))
3677 free_block_structure(last_cages);
3678 if (good_cages != NULL) {
3679 free_block_structure(kblocks);
3680 kblocks = good_cages;
3681 compute_kclues(kblocks, kgrid, grid2, area);
3682 memset(grid, 0, area * sizeof *grid);
3689 * Find the set of equivalence classes of squares permitted
3690 * by the selected symmetry. We do this by enumerating all
3691 * the grid squares which have no symmetric companion
3692 * sorting lower than themselves.
3695 for (y = 0; y < cr; y++)
3696 for (x = 0; x < cr; x++) {
3700 ncoords = symmetries(params, x, y, coords, params->symm);
3701 for (j = 0; j < ncoords; j++)
3702 if (coords[2*j+1]*cr+coords[2*j] < i)
3712 * Now shuffle that list.
3714 shuffle(locs, nlocs, sizeof(*locs), rs);
3717 * Now loop over the shuffled list and, for each element,
3718 * see whether removing that element (and its reflections)
3719 * from the grid will still leave the grid soluble.
3721 for (i = 0; i < nlocs; i++) {
3725 memcpy(grid2, grid, area);
3726 ncoords = symmetries(params, x, y, coords, params->symm);
3727 for (j = 0; j < ncoords; j++)
3728 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
3730 solver(cr, blocks, kblocks, params->xtype, grid2, kgrid, &dlev);
3731 if (dlev.diff <= dlev.maxdiff &&
3732 (!params->killer || dlev.kdiff <= dlev.maxkdiff)) {
3733 for (j = 0; j < ncoords; j++)
3734 grid[coords[2*j+1]*cr+coords[2*j]] = 0;
3738 memcpy(grid2, grid, area);
3740 solver(cr, blocks, kblocks, params->xtype, grid2, kgrid, &dlev);
3741 if (dlev.diff == dlev.maxdiff &&
3742 (!params->killer || dlev.kdiff == dlev.maxkdiff))
3743 break; /* found one! */
3750 * Now we have the grid as it will be presented to the user.
3751 * Encode it in a game desc.
3753 desc = encode_puzzle_desc(params, grid, blocks, kgrid, kblocks);
3760 static char *spec_to_grid(char *desc, digit *grid, int area)
3763 while (*desc && *desc != ',') {
3765 if (n >= 'a' && n <= 'z') {
3766 int run = n - 'a' + 1;
3767 assert(i + run <= area);
3770 } else if (n == '_') {
3772 } else if (n > '0' && n <= '9') {
3774 grid[i++] = atoi(desc-1);
3775 while (*desc >= '0' && *desc <= '9')
3778 assert(!"We can't get here");
3786 * Create a DSF from a spec found in *pdesc. Update this to point past the
3787 * end of the block spec, and return an error string or NULL if everything
3788 * is OK. The DSF is stored in *PDSF.
3790 static char *spec_to_dsf(char **pdesc, int **pdsf, int cr, int area)
3792 char *desc = *pdesc;
3796 *pdsf = dsf = snew_dsf(area);
3798 while (*desc && *desc != ',') {
3803 else if (*desc >= 'a' && *desc <= 'z')
3804 c = *desc - 'a' + 1;
3807 return "Invalid character in game description";
3811 adv = (c != 25); /* 'z' is a special case */
3817 * Non-edge; merge the two dsf classes on either
3820 assert(pos < 2*cr*(cr-1));
3821 if (pos < cr*(cr-1)) {
3827 int x = pos/(cr-1) - cr;
3832 dsf_merge(dsf, p0, p1);
3842 * When desc is exhausted, we expect to have gone exactly
3843 * one space _past_ the end of the grid, due to the dummy
3846 if (pos != 2*cr*(cr-1)+1) {
3848 return "Not enough data in block structure specification";
3854 static char *validate_grid_desc(char **pdesc, int range, int area)
3856 char *desc = *pdesc;
3858 while (*desc && *desc != ',') {
3860 if (n >= 'a' && n <= 'z') {
3861 squares += n - 'a' + 1;
3862 } else if (n == '_') {
3864 } else if (n > '0' && n <= '9') {
3865 int val = atoi(desc-1);
3866 if (val < 1 || val > range)
3867 return "Out-of-range number in game description";
3869 while (*desc >= '0' && *desc <= '9')
3872 return "Invalid character in game description";
3876 return "Not enough data to fill grid";
3879 return "Too much data to fit in grid";
3884 static char *validate_block_desc(char **pdesc, int cr, int area,
3885 int min_nr_blocks, int max_nr_blocks,
3886 int min_nr_squares, int max_nr_squares)
3891 err = spec_to_dsf(pdesc, &dsf, cr, area);
3896 if (min_nr_squares == max_nr_squares) {
3897 assert(min_nr_blocks == max_nr_blocks);
3898 assert(min_nr_blocks * min_nr_squares == area);
3901 * Now we've got our dsf. Verify that it matches
3905 int *canons, *counts;
3906 int i, j, c, ncanons = 0;
3908 canons = snewn(max_nr_blocks, int);
3909 counts = snewn(max_nr_blocks, int);
3911 for (i = 0; i < area; i++) {
3912 j = dsf_canonify(dsf, i);
3914 for (c = 0; c < ncanons; c++)
3915 if (canons[c] == j) {
3917 if (counts[c] > max_nr_squares) {
3921 return "A jigsaw block is too big";
3927 if (ncanons >= max_nr_blocks) {
3931 return "Too many distinct jigsaw blocks";
3933 canons[ncanons] = j;
3934 counts[ncanons] = 1;
3939 if (ncanons < min_nr_blocks) {
3943 return "Not enough distinct jigsaw blocks";
3945 for (c = 0; c < ncanons; c++) {
3946 if (counts[c] < min_nr_squares) {
3950 return "A jigsaw block is too small";
3961 static char *validate_desc(game_params *params, char *desc)
3963 int cr = params->c * params->r, area = cr*cr;
3966 err = validate_grid_desc(&desc, cr, area);
3970 if (params->r == 1) {
3972 * Now we expect a suffix giving the jigsaw block
3973 * structure. Parse it and validate that it divides the
3974 * grid into the right number of regions which are the
3978 return "Expected jigsaw block structure in game description";
3980 err = validate_block_desc(&desc, cr, area, cr, cr, cr, cr);
3985 if (params->killer) {
3987 return "Expected killer block structure in game description";
3989 err = validate_block_desc(&desc, cr, area, cr, area, 2, cr);
3993 return "Expected killer clue grid in game description";
3995 err = validate_grid_desc(&desc, cr * area, area);
4000 return "Unexpected data at end of game description";
4005 static game_state *new_game(midend *me, game_params *params, char *desc)
4007 game_state *state = snew(game_state);
4008 int c = params->c, r = params->r, cr = c*r, area = cr * cr;
4011 precompute_sum_bits();
4014 state->xtype = params->xtype;
4015 state->killer = params->killer;
4017 state->grid = snewn(area, digit);
4018 state->pencil = snewn(area * cr, unsigned char);
4019 memset(state->pencil, 0, area * cr);
4020 state->immutable = snewn(area, unsigned char);
4021 memset(state->immutable, FALSE, area);
4023 state->blocks = alloc_block_structure (c, r, area, cr, cr);
4025 if (params->killer) {
4026 state->kblocks = alloc_block_structure (c, r, area, cr, area);
4027 state->kgrid = snewn(area, digit);
4029 state->kblocks = NULL;
4030 state->kgrid = NULL;
4032 state->completed = state->cheated = FALSE;
4034 desc = spec_to_grid(desc, state->grid, area);
4035 for (i = 0; i < area; i++)
4036 if (state->grid[i] != 0)
4037 state->immutable[i] = TRUE;
4042 assert(*desc == ',');
4044 err = spec_to_dsf(&desc, &dsf, cr, area);
4045 assert(err == NULL);
4046 dsf_to_blocks(dsf, state->blocks, cr, cr);
4051 for (y = 0; y < cr; y++)
4052 for (x = 0; x < cr; x++)
4053 state->blocks->whichblock[y*cr+x] = (y/c) * c + (x/r);
4055 make_blocks_from_whichblock(state->blocks);
4057 if (params->killer) {
4060 assert(*desc == ',');
4062 err = spec_to_dsf(&desc, &dsf, cr, area);
4063 assert(err == NULL);
4064 dsf_to_blocks(dsf, state->kblocks, cr, area);
4066 make_blocks_from_whichblock(state->kblocks);
4068 assert(*desc == ',');
4070 desc = spec_to_grid(desc, state->kgrid, area);
4074 #ifdef STANDALONE_SOLVER
4076 * Set up the block names for solver diagnostic output.
4079 char *p = (char *)(state->blocks->blocknames + cr);
4082 for (i = 0; i < area; i++) {
4083 int j = state->blocks->whichblock[i];
4084 if (!state->blocks->blocknames[j]) {
4085 state->blocks->blocknames[j] = p;
4086 p += 1 + sprintf(p, "starting at (%d,%d)",
4087 1 + i%cr, 1 + i/cr);
4092 for (by = 0; by < r; by++)
4093 for (bx = 0; bx < c; bx++) {
4094 state->blocks->blocknames[by*c+bx] = p;
4095 p += 1 + sprintf(p, "(%d,%d)", bx+1, by+1);
4098 assert(p - (char *)state->blocks->blocknames < (int)(cr*(sizeof(char *)+80)));
4099 for (i = 0; i < cr; i++)
4100 assert(state->blocks->blocknames[i]);
4107 static game_state *dup_game(game_state *state)
4109 game_state *ret = snew(game_state);
4110 int cr = state->cr, area = cr * cr;
4112 ret->cr = state->cr;
4113 ret->xtype = state->xtype;
4114 ret->killer = state->killer;
4116 ret->blocks = state->blocks;
4117 ret->blocks->refcount++;
4119 ret->kblocks = state->kblocks;
4121 ret->kblocks->refcount++;
4123 ret->grid = snewn(area, digit);
4124 memcpy(ret->grid, state->grid, area);
4126 if (state->killer) {
4127 ret->kgrid = snewn(area, digit);
4128 memcpy(ret->kgrid, state->kgrid, area);
4132 ret->pencil = snewn(area * cr, unsigned char);
4133 memcpy(ret->pencil, state->pencil, area * cr);
4135 ret->immutable = snewn(area, unsigned char);
4136 memcpy(ret->immutable, state->immutable, area);
4138 ret->completed = state->completed;
4139 ret->cheated = state->cheated;
4144 static void free_game(game_state *state)
4146 free_block_structure(state->blocks);
4148 free_block_structure(state->kblocks);
4150 sfree(state->immutable);
4151 sfree(state->pencil);
4156 static char *solve_game(game_state *state, game_state *currstate,
4157 char *ai, char **error)
4162 struct difficulty dlev;
4165 * If we already have the solution in ai, save ourselves some
4171 grid = snewn(cr*cr, digit);
4172 memcpy(grid, state->grid, cr*cr);
4173 dlev.maxdiff = DIFF_RECURSIVE;
4174 dlev.maxkdiff = DIFF_KINTERSECT;
4175 solver(cr, state->blocks, state->kblocks, state->xtype, grid,
4176 state->kgrid, &dlev);
4180 if (dlev.diff == DIFF_IMPOSSIBLE)
4181 *error = "No solution exists for this puzzle";
4182 else if (dlev.diff == DIFF_AMBIGUOUS)
4183 *error = "Multiple solutions exist for this puzzle";
4190 ret = encode_solve_move(cr, grid);
4197 static char *grid_text_format(int cr, struct block_structure *blocks,
4198 int xtype, digit *grid)
4202 int totallen, linelen, nlines;
4206 * For non-jigsaw Sudoku, we format in the way we always have,
4207 * by having the digits unevenly spaced so that the dividing
4216 * For jigsaw puzzles, however, we must leave space between
4217 * _all_ pairs of digits for an optional dividing line, so we
4218 * have to move to the rather ugly
4228 * We deal with both cases using the same formatting code; we
4229 * simply invent a vmod value such that there's a vertical
4230 * dividing line before column i iff i is divisible by vmod
4231 * (so it's r in the first case and 1 in the second), and hmod
4232 * likewise for horizontal dividing lines.
4235 if (blocks->r != 1) {
4243 * Line length: we have cr digits, each with a space after it,
4244 * and (cr-1)/vmod dividing lines, each with a space after it.
4245 * The final space is replaced by a newline, but that doesn't
4246 * affect the length.
4248 linelen = 2*(cr + (cr-1)/vmod);
4251 * Number of lines: we have cr rows of digits, and (cr-1)/hmod
4254 nlines = cr + (cr-1)/hmod;
4257 * Allocate the space.
4259 totallen = linelen * nlines;
4260 ret = snewn(totallen+1, char); /* leave room for terminating NUL */
4266 for (y = 0; y < cr; y++) {
4270 for (x = 0; x < cr; x++) {
4274 digit d = grid[y*cr+x];
4278 * Empty space: we usually write a dot, but we'll
4279 * highlight spaces on the X-diagonals (in X mode)
4280 * by using underscores instead.
4282 if (xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x)))
4286 } else if (d <= 9) {
4303 * Optional dividing line.
4305 if (blocks->whichblock[y*cr+x] != blocks->whichblock[y*cr+x+1])
4312 if (y == cr-1 || (y+1) % hmod)
4318 for (x = 0; x < cr; x++) {
4323 * Division between two squares. This varies
4324 * complicatedly in length.
4326 dwid = 2; /* digit and its following space */
4328 dwid--; /* no following space at end of line */
4329 if (x > 0 && x % vmod == 0)
4330 dwid++; /* preceding space after a divider */
4332 if (blocks->whichblock[y*cr+x] != blocks->whichblock[(y+1)*cr+x])
4349 * Corner square. This is:
4350 * - a space if all four surrounding squares are in
4352 * - a vertical line if the two left ones are in one
4353 * block and the two right in another
4354 * - a horizontal line if the two top ones are in one
4355 * block and the two bottom in another
4356 * - a plus sign in all other cases. (If we had a
4357 * richer character set available we could break
4358 * this case up further by doing fun things with
4359 * line-drawing T-pieces.)
4361 tl = blocks->whichblock[y*cr+x];
4362 tr = blocks->whichblock[y*cr+x+1];
4363 bl = blocks->whichblock[(y+1)*cr+x];
4364 br = blocks->whichblock[(y+1)*cr+x+1];
4366 if (tl == tr && tr == bl && bl == br)
4368 else if (tl == bl && tr == br)
4370 else if (tl == tr && bl == br)
4379 assert(p - ret == totallen);
4384 static int game_can_format_as_text_now(game_params *params)
4387 * Formatting Killer puzzles as text is currently unsupported. I
4388 * can't think of any sensible way of doing it which doesn't
4389 * involve expanding the puzzle to such a large scale as to make
4397 static char *game_text_format(game_state *state)
4399 assert(!state->kblocks);
4400 return grid_text_format(state->cr, state->blocks, state->xtype,
4406 * These are the coordinates of the currently highlighted
4407 * square on the grid, if hshow = 1.
4411 * This indicates whether the current highlight is a
4412 * pencil-mark one or a real one.
4416 * This indicates whether or not we're showing the highlight
4417 * (used to be hx = hy = -1); important so that when we're
4418 * using the cursor keys it doesn't keep coming back at a
4419 * fixed position. When hshow = 1, pressing a valid number
4420 * or letter key or Space will enter that number or letter in the grid.
4424 * This indicates whether we're using the highlight as a cursor;
4425 * it means that it doesn't vanish on a keypress, and that it is
4426 * allowed on immutable squares.
4431 static game_ui *new_ui(game_state *state)
4433 game_ui *ui = snew(game_ui);
4435 ui->hx = ui->hy = 0;
4436 ui->hpencil = ui->hshow = ui->hcursor = 0;
4441 static void free_ui(game_ui *ui)
4446 static char *encode_ui(game_ui *ui)
4451 static void decode_ui(game_ui *ui, char *encoding)
4455 static void game_changed_state(game_ui *ui, game_state *oldstate,
4456 game_state *newstate)
4458 int cr = newstate->cr;
4460 * We prevent pencil-mode highlighting of a filled square, unless
4461 * we're using the cursor keys. So if the user has just filled in
4462 * a square which we had a pencil-mode highlight in (by Undo, or
4463 * by Redo, or by Solve), then we cancel the highlight.
4465 if (ui->hshow && ui->hpencil && !ui->hcursor &&
4466 newstate->grid[ui->hy * cr + ui->hx] != 0) {
4471 struct game_drawstate {
4476 unsigned char *pencil;
4478 /* This is scratch space used within a single call to game_redraw. */
4479 int nregions, *entered_items;
4482 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
4483 int x, int y, int button)
4489 button &= ~MOD_MASK;
4491 tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
4492 ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
4494 if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
4495 if (button == LEFT_BUTTON) {
4496 if (state->immutable[ty*cr+tx]) {
4498 } else if (tx == ui->hx && ty == ui->hy &&
4499 ui->hshow && ui->hpencil == 0) {
4508 return ""; /* UI activity occurred */
4510 if (button == RIGHT_BUTTON) {
4512 * Pencil-mode highlighting for non filled squares.
4514 if (state->grid[ty*cr+tx] == 0) {
4515 if (tx == ui->hx && ty == ui->hy &&
4516 ui->hshow && ui->hpencil) {
4528 return ""; /* UI activity occurred */
4531 if (IS_CURSOR_MOVE(button)) {
4532 move_cursor(button, &ui->hx, &ui->hy, cr, cr, 0);
4533 ui->hshow = ui->hcursor = 1;
4537 (button == CURSOR_SELECT)) {
4538 ui->hpencil = 1 - ui->hpencil;
4544 ((button >= '0' && button <= '9' && button - '0' <= cr) ||
4545 (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
4546 (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
4547 button == CURSOR_SELECT2 || button == '\010' || button == '\177')) {
4548 int n = button - '0';
4549 if (button >= 'A' && button <= 'Z')
4550 n = button - 'A' + 10;
4551 if (button >= 'a' && button <= 'z')
4552 n = button - 'a' + 10;
4553 if (button == CURSOR_SELECT2 || button == '\010' || button == '\177')
4557 * Can't overwrite this square. This can only happen here
4558 * if we're using the cursor keys.
4560 if (state->immutable[ui->hy*cr+ui->hx])
4564 * Can't make pencil marks in a filled square. Again, this
4565 * can only become highlighted if we're using cursor keys.
4567 if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
4570 sprintf(buf, "%c%d,%d,%d",
4571 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
4573 if (!ui->hcursor) ui->hshow = 0;
4581 static game_state *execute_move(game_state *from, char *move)
4587 if (move[0] == 'S') {
4590 ret = dup_game(from);
4591 ret->completed = ret->cheated = TRUE;
4594 for (n = 0; n < cr*cr; n++) {
4595 ret->grid[n] = atoi(p);
4597 if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
4602 while (*p && isdigit((unsigned char)*p)) p++;
4607 } else if ((move[0] == 'P' || move[0] == 'R') &&
4608 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
4609 x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
4611 ret = dup_game(from);
4612 if (move[0] == 'P' && n > 0) {
4613 int index = (y*cr+x) * cr + (n-1);
4614 ret->pencil[index] = !ret->pencil[index];
4616 ret->grid[y*cr+x] = n;
4617 memset(ret->pencil + (y*cr+x)*cr, 0, cr);
4620 * We've made a real change to the grid. Check to see
4621 * if the game has been completed.
4623 if (!ret->completed && check_valid(cr, ret->blocks, ret->kblocks,
4624 ret->xtype, ret->grid)) {
4625 ret->completed = TRUE;
4630 return NULL; /* couldn't parse move string */
4633 /* ----------------------------------------------------------------------
4637 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
4638 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
4640 static void game_compute_size(game_params *params, int tilesize,
4643 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
4644 struct { int tilesize; } ads, *ds = &ads;
4645 ads.tilesize = tilesize;
4647 *x = SIZE(params->c * params->r);
4648 *y = SIZE(params->c * params->r);
4651 static void game_set_size(drawing *dr, game_drawstate *ds,
4652 game_params *params, int tilesize)
4654 ds->tilesize = tilesize;
4657 static float *game_colours(frontend *fe, int *ncolours)
4659 float *ret = snewn(3 * NCOLOURS, float);
4661 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
4663 ret[COL_XDIAGONALS * 3 + 0] = 0.9F * ret[COL_BACKGROUND * 3 + 0];
4664 ret[COL_XDIAGONALS * 3 + 1] = 0.9F * ret[COL_BACKGROUND * 3 + 1];
4665 ret[COL_XDIAGONALS * 3 + 2] = 0.9F * ret[COL_BACKGROUND * 3 + 2];
4667 ret[COL_GRID * 3 + 0] = 0.0F;
4668 ret[COL_GRID * 3 + 1] = 0.0F;
4669 ret[COL_GRID * 3 + 2] = 0.0F;
4671 ret[COL_CLUE * 3 + 0] = 0.0F;
4672 ret[COL_CLUE * 3 + 1] = 0.0F;
4673 ret[COL_CLUE * 3 + 2] = 0.0F;
4675 ret[COL_USER * 3 + 0] = 0.0F;
4676 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
4677 ret[COL_USER * 3 + 2] = 0.0F;
4679 ret[COL_HIGHLIGHT * 3 + 0] = 0.78F * ret[COL_BACKGROUND * 3 + 0];
4680 ret[COL_HIGHLIGHT * 3 + 1] = 0.78F * ret[COL_BACKGROUND * 3 + 1];
4681 ret[COL_HIGHLIGHT * 3 + 2] = 0.78F * ret[COL_BACKGROUND * 3 + 2];
4683 ret[COL_ERROR * 3 + 0] = 1.0F;
4684 ret[COL_ERROR * 3 + 1] = 0.0F;
4685 ret[COL_ERROR * 3 + 2] = 0.0F;
4687 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
4688 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
4689 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
4691 ret[COL_KILLER * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
4692 ret[COL_KILLER * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
4693 ret[COL_KILLER * 3 + 2] = 0.1F * ret[COL_BACKGROUND * 3 + 2];
4695 *ncolours = NCOLOURS;
4699 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
4701 struct game_drawstate *ds = snew(struct game_drawstate);
4704 ds->started = FALSE;
4706 ds->xtype = state->xtype;
4707 ds->grid = snewn(cr*cr, digit);
4708 memset(ds->grid, cr+2, cr*cr);
4709 ds->pencil = snewn(cr*cr*cr, digit);
4710 memset(ds->pencil, 0, cr*cr*cr);
4711 ds->hl = snewn(cr*cr, unsigned char);
4712 memset(ds->hl, 0, cr*cr);
4714 * ds->entered_items needs one row of cr entries per entity in
4715 * which digits may not be duplicated. That's one for each row,
4716 * each column, each block, each diagonal, and each Killer cage.
4718 ds->nregions = cr*3 + 2;
4720 ds->nregions += state->kblocks->nr_blocks;
4721 ds->entered_items = snewn(cr * ds->nregions, int);
4722 ds->tilesize = 0; /* not decided yet */
4726 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
4731 sfree(ds->entered_items);
4735 static void draw_number(drawing *dr, game_drawstate *ds, game_state *state,
4736 int x, int y, int hl)
4741 int col_killer = (hl & 32 ? COL_ERROR : COL_KILLER);
4744 if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
4745 ds->hl[y*cr+x] == hl &&
4746 !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
4747 return; /* no change required */
4749 tx = BORDER + x * TILE_SIZE + 1 + GRIDEXTRA;
4750 ty = BORDER + y * TILE_SIZE + 1 + GRIDEXTRA;
4754 cw = tw = TILE_SIZE-1-2*GRIDEXTRA;
4755 ch = th = TILE_SIZE-1-2*GRIDEXTRA;
4757 if (x > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x-1])
4758 cx -= GRIDEXTRA, cw += GRIDEXTRA;
4759 if (x+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[y*cr+x+1])
4761 if (y > 0 && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y-1)*cr+x])
4762 cy -= GRIDEXTRA, ch += GRIDEXTRA;
4763 if (y+1 < cr && state->blocks->whichblock[y*cr+x] == state->blocks->whichblock[(y+1)*cr+x])
4766 clip(dr, cx, cy, cw, ch);
4768 /* background needs erasing */
4769 draw_rect(dr, cx, cy, cw, ch,
4770 ((hl & 15) == 1 ? COL_HIGHLIGHT :
4771 (ds->xtype && (ondiag0(y*cr+x) || ondiag1(y*cr+x))) ? COL_XDIAGONALS :
4775 * Draw the corners of thick lines in corner-adjacent squares,
4776 * which jut into this square by one pixel.
4778 if (x > 0 && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x-1])
4779 draw_rect(dr, tx-GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4780 if (x+1 < cr && y > 0 && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y-1)*cr+x+1])
4781 draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty-GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4782 if (x > 0 && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x-1])
4783 draw_rect(dr, tx-GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4784 if (x+1 < cr && y+1 < cr && state->blocks->whichblock[y*cr+x] != state->blocks->whichblock[(y+1)*cr+x+1])
4785 draw_rect(dr, tx+TILE_SIZE-1-2*GRIDEXTRA, ty+TILE_SIZE-1-2*GRIDEXTRA, GRIDEXTRA, GRIDEXTRA, COL_GRID);
4787 /* pencil-mode highlight */
4788 if ((hl & 15) == 2) {
4792 coords[2] = cx+cw/2;
4795 coords[5] = cy+ch/2;
4796 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
4799 if (state->kblocks) {
4800 int t = GRIDEXTRA * 3;
4801 int kcx, kcy, kcw, kch;
4803 int has_left = 0, has_right = 0, has_top = 0, has_bottom = 0;
4806 * In non-jigsaw mode, the Killer cages are placed at a
4807 * fixed offset from the outer edge of the cell dividing
4808 * lines, so that they look right whether those lines are
4809 * thick or thin. In jigsaw mode, however, doing this will
4810 * sometimes cause the cage outlines in adjacent squares to
4811 * fail to match up with each other, so we must offset a
4812 * fixed amount from the _centre_ of the cell dividing
4815 if (state->blocks->r == 1) {
4832 * First, draw the lines dividing this area from neighbouring
4835 if (x == 0 || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[y*cr+x-1])
4836 has_left = 1, kl += t;
4837 if (x+1 >= cr || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[y*cr+x+1])
4838 has_right = 1, kr -= t;
4839 if (y == 0 || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x])
4840 has_top = 1, kt += t;
4841 if (y+1 >= cr || state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x])
4842 has_bottom = 1, kb -= t;
4844 draw_line(dr, kl, kt, kr, kt, col_killer);
4846 draw_line(dr, kl, kb, kr, kb, col_killer);
4848 draw_line(dr, kl, kt, kl, kb, col_killer);
4850 draw_line(dr, kr, kt, kr, kb, col_killer);
4852 * Now, take care of the corners (just as for the normal borders).
4853 * We only need a corner if there wasn't a full edge.
4855 if (x > 0 && y > 0 && !has_left && !has_top
4856 && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x-1])
4858 draw_line(dr, kl, kt + t, kl + t, kt + t, col_killer);
4859 draw_line(dr, kl + t, kt, kl + t, kt + t, col_killer);
4861 if (x+1 < cr && y > 0 && !has_right && !has_top
4862 && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y-1)*cr+x+1])
4864 draw_line(dr, kcx + kcw - t, kt + t, kcx + kcw, kt + t, col_killer);
4865 draw_line(dr, kcx + kcw - t, kt, kcx + kcw - t, kt + t, col_killer);
4867 if (x > 0 && y+1 < cr && !has_left && !has_bottom
4868 && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x-1])
4870 draw_line(dr, kl, kcy + kch - t, kl + t, kcy + kch - t, col_killer);
4871 draw_line(dr, kl + t, kcy + kch - t, kl + t, kcy + kch, col_killer);
4873 if (x+1 < cr && y+1 < cr && !has_right && !has_bottom
4874 && state->kblocks->whichblock[y*cr+x] != state->kblocks->whichblock[(y+1)*cr+x+1])
4876 draw_line(dr, kcx + kcw - t, kcy + kch - t, kcx + kcw - t, kcy + kch, col_killer);
4877 draw_line(dr, kcx + kcw - t, kcy + kch - t, kcx + kcw, kcy + kch - t, col_killer);
4882 if (state->killer && state->kgrid[y*cr+x]) {
4883 sprintf (str, "%d", state->kgrid[y*cr+x]);
4884 draw_text(dr, tx + GRIDEXTRA * 4, ty + GRIDEXTRA * 4 + TILE_SIZE/4,
4885 FONT_VARIABLE, TILE_SIZE/4, ALIGN_VNORMAL | ALIGN_HLEFT,
4889 /* new number needs drawing? */
4890 if (state->grid[y*cr+x]) {
4892 str[0] = state->grid[y*cr+x] + '0';
4894 str[0] += 'a' - ('9'+1);
4895 draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
4896 FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
4897 state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
4902 int pw, ph, minph, pbest, fontsize;
4904 /* Count the pencil marks required. */
4905 for (i = npencil = 0; i < cr; i++)
4906 if (state->pencil[(y*cr+x)*cr+i])
4913 * Determine the bounding rectangle within which we're going
4914 * to put the pencil marks.
4916 /* Start with the whole square */
4917 pl = tx + GRIDEXTRA;
4918 pr = pl + TILE_SIZE - GRIDEXTRA;
4919 pt = ty + GRIDEXTRA;
4920 pb = pt + TILE_SIZE - GRIDEXTRA;
4921 if (state->killer) {
4923 * Make space for the Killer cages. We do this
4924 * unconditionally, for uniformity between squares,
4925 * rather than making it depend on whether a Killer
4926 * cage edge is actually present on any given side.
4928 pl += GRIDEXTRA * 3;
4929 pr -= GRIDEXTRA * 3;
4930 pt += GRIDEXTRA * 3;
4931 pb -= GRIDEXTRA * 3;
4932 if (state->kgrid[y*cr+x] != 0) {
4933 /* Make further space for the Killer number. */
4940 * We arrange our pencil marks in a grid layout, with
4941 * the number of rows and columns adjusted to allow the
4942 * maximum font size.
4944 * So now we work out what the grid size ought to be.
4949 for (pw = 3; pw < max(npencil,4); pw++) {
4952 ph = (npencil + pw - 1) / pw;
4953 ph = max(ph, minph);
4954 fw = (pr - pl) / (float)pw;
4955 fh = (pb - pt) / (float)ph;
4957 if (fs > bestsize) {
4964 ph = (npencil + pw - 1) / pw;
4965 ph = max(ph, minph);
4968 * Now we've got our grid dimensions, work out the pixel
4969 * size of a grid element, and round it to the nearest
4970 * pixel. (We don't want rounding errors to make the
4971 * grid look uneven at low pixel sizes.)
4973 fontsize = min((pr - pl) / pw, (pb - pt) / ph);
4976 * Centre the resulting figure in the square.
4978 pl = tx + (TILE_SIZE - fontsize * pw) / 2;
4979 pt = ty + (TILE_SIZE - fontsize * ph) / 2;
4982 * And move it down a bit if it's collided with the
4983 * Killer cage number.
4985 if (state->killer && state->kgrid[y*cr+x] != 0) {
4986 pt = max(pt, ty + GRIDEXTRA * 3 + TILE_SIZE/4);
4990 * Now actually draw the pencil marks.
4992 for (i = j = 0; i < cr; i++)
4993 if (state->pencil[(y*cr+x)*cr+i]) {
4994 int dx = j % pw, dy = j / pw;
4999 str[0] += 'a' - ('9'+1);
5000 draw_text(dr, pl + fontsize * (2*dx+1) / 2,
5001 pt + fontsize * (2*dy+1) / 2,
5002 FONT_VARIABLE, fontsize,
5003 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
5011 draw_update(dr, cx, cy, cw, ch);
5013 ds->grid[y*cr+x] = state->grid[y*cr+x];
5014 memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
5015 ds->hl[y*cr+x] = hl;
5018 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
5019 game_state *state, int dir, game_ui *ui,
5020 float animtime, float flashtime)
5027 * The initial contents of the window are not guaranteed
5028 * and can vary with front ends. To be on the safe side,
5029 * all games should start by drawing a big
5030 * background-colour rectangle covering the whole window.
5032 draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
5035 * Draw the grid. We draw it as a big thick rectangle of
5036 * COL_GRID initially; individual calls to draw_number()
5037 * will poke the right-shaped holes in it.
5039 draw_rect(dr, BORDER-GRIDEXTRA, BORDER-GRIDEXTRA,
5040 cr*TILE_SIZE+1+2*GRIDEXTRA, cr*TILE_SIZE+1+2*GRIDEXTRA,
5045 * This array is used to keep track of rows, columns and boxes
5046 * which contain a number more than once.
5048 for (x = 0; x < cr * ds->nregions; x++)
5049 ds->entered_items[x] = 0;
5050 for (x = 0; x < cr; x++)
5051 for (y = 0; y < cr; y++) {
5052 digit d = state->grid[y*cr+x];
5057 ds->entered_items[x*cr+d-1]++;
5060 ds->entered_items[(y+cr)*cr+d-1]++;
5063 box = state->blocks->whichblock[y*cr+x];
5064 ds->entered_items[(box+2*cr)*cr+d-1]++;
5068 if (ondiag0(y*cr+x))
5069 ds->entered_items[(3*cr)*cr+d-1]++;
5070 if (ondiag1(y*cr+x))
5071 ds->entered_items[(3*cr+1)*cr+d-1]++;
5075 if (state->kblocks) {
5076 kbox = state->kblocks->whichblock[y*cr+x];
5077 ds->entered_items[(kbox+3*cr+2)*cr+d-1]++;
5083 * Draw any numbers which need redrawing.
5085 for (x = 0; x < cr; x++) {
5086 for (y = 0; y < cr; y++) {
5088 digit d = state->grid[y*cr+x];
5090 if (flashtime > 0 &&
5091 (flashtime <= FLASH_TIME/3 ||
5092 flashtime >= FLASH_TIME*2/3))
5095 /* Highlight active input areas. */
5096 if (x == ui->hx && y == ui->hy && ui->hshow)
5097 highlight = ui->hpencil ? 2 : 1;
5099 /* Mark obvious errors (ie, numbers which occur more than once
5100 * in a single row, column, or box). */
5101 if (d && (ds->entered_items[x*cr+d-1] > 1 ||
5102 ds->entered_items[(y+cr)*cr+d-1] > 1 ||
5103 ds->entered_items[(state->blocks->whichblock[y*cr+x]
5104 +2*cr)*cr+d-1] > 1 ||
5105 (ds->xtype && ((ondiag0(y*cr+x) &&
5106 ds->entered_items[(3*cr)*cr+d-1] > 1) ||
5108 ds->entered_items[(3*cr+1)*cr+d-1]>1)))||
5110 ds->entered_items[(state->kblocks->whichblock[y*cr+x]
5111 +3*cr+2)*cr+d-1] > 1)))
5114 if (d && state->kblocks) {
5115 int i, b = state->kblocks->whichblock[y*cr+x];
5116 int n_squares = state->kblocks->nr_squares[b];
5117 int sum = 0, clue = 0;
5118 for (i = 0; i < n_squares; i++) {
5119 int xy = state->kblocks->blocks[b][i];
5120 if (state->grid[xy] == 0)
5123 sum += state->grid[xy];
5124 if (state->kgrid[xy]) {
5126 clue = state->kgrid[xy];
5130 if (i == n_squares) {
5137 draw_number(dr, ds, state, x, y, highlight);
5142 * Update the _entire_ grid if necessary.
5145 draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
5150 static float game_anim_length(game_state *oldstate, game_state *newstate,
5151 int dir, game_ui *ui)
5156 static float game_flash_length(game_state *oldstate, game_state *newstate,
5157 int dir, game_ui *ui)
5159 if (!oldstate->completed && newstate->completed &&
5160 !oldstate->cheated && !newstate->cheated)
5165 static int game_timing_state(game_state *state, game_ui *ui)
5167 if (state->completed)
5172 static void game_print_size(game_params *params, float *x, float *y)
5177 * I'll use 9mm squares by default. They should be quite big
5178 * for this game, because players will want to jot down no end
5179 * of pencil marks in the squares.
5181 game_compute_size(params, 900, &pw, &ph);
5187 * Subfunction to draw the thick lines between cells. In order to do
5188 * this using the line-drawing rather than rectangle-drawing API (so
5189 * as to get line thicknesses to scale correctly) and yet have
5190 * correctly mitred joins between lines, we must do this by tracing
5191 * the boundary of each sub-block and drawing it in one go as a
5194 * This subfunction is also reused with thinner dotted lines to
5195 * outline the Killer cages, this time offsetting the outline toward
5196 * the interior of the affected squares.
5198 static void outline_block_structure(drawing *dr, game_drawstate *ds,
5200 struct block_structure *blocks,
5206 int x, y, dx, dy, sx, sy, sdx, sdy;
5209 * Maximum perimeter of a k-omino is 2k+2. (Proof: start
5210 * with k unconnected squares, with total perimeter 4k.
5211 * Now repeatedly join two disconnected components
5212 * together into a larger one; every time you do so you
5213 * remove at least two unit edges, and you require k-1 of
5214 * these operations to create a single connected piece, so
5215 * you must have at most 4k-2(k-1) = 2k+2 unit edges left
5218 coords = snewn(4*cr+4, int); /* 2k+2 points, 2 coords per point */
5221 * Iterate over all the blocks.
5223 for (bi = 0; bi < blocks->nr_blocks; bi++) {
5224 if (blocks->nr_squares[bi] == 0)
5228 * For each block, find a starting square within it
5229 * which has a boundary at the left.
5231 for (i = 0; i < cr; i++) {
5232 int j = blocks->blocks[bi][i];
5233 if (j % cr == 0 || blocks->whichblock[j-1] != bi)
5236 assert(i < cr); /* every block must have _some_ leftmost square */
5237 x = blocks->blocks[bi][i] % cr;
5238 y = blocks->blocks[bi][i] / cr;
5243 * Now begin tracing round the perimeter. At all
5244 * times, (x,y) describes some square within the
5245 * block, and (x+dx,y+dy) is some adjacent square
5246 * outside it; so the edge between those two squares
5247 * is always an edge of the block.
5249 sx = x, sy = y, sdx = dx, sdy = dy; /* save starting position */
5252 int cx, cy, tx, ty, nin;
5255 * Advance to the next edge, by looking at the two
5256 * squares beyond it. If they're both outside the block,
5257 * we turn right (by leaving x,y the same and rotating
5258 * dx,dy clockwise); if they're both inside, we turn
5259 * left (by rotating dx,dy anticlockwise and contriving
5260 * to leave x+dx,y+dy unchanged); if one of each, we go
5261 * straight on (and may enforce by assertion that
5262 * they're one of each the _right_ way round).
5267 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
5268 blocks->whichblock[ty*cr+tx] == bi);
5271 nin += (tx >= 0 && tx < cr && ty >= 0 && ty < cr &&
5272 blocks->whichblock[ty*cr+tx] == bi);
5281 } else if (nin == 2) {
5305 * Now enforce by assertion that we ended up
5306 * somewhere sensible.
5308 assert(x >= 0 && x < cr && y >= 0 && y < cr &&
5309 blocks->whichblock[y*cr+x] == bi);
5310 assert(x+dx < 0 || x+dx >= cr || y+dy < 0 || y+dy >= cr ||
5311 blocks->whichblock[(y+dy)*cr+(x+dx)] != bi);
5314 * Record the point we just went past at one end of the
5315 * edge. To do this, we translate (x,y) down and right
5316 * by half a unit (so they're describing a point in the
5317 * _centre_ of the square) and then translate back again
5318 * in a manner rotated by dy and dx.
5321 cx = ((2*x+1) + dy + dx) / 2;
5322 cy = ((2*y+1) - dx + dy) / 2;
5323 coords[2*n+0] = BORDER + cx * TILE_SIZE;
5324 coords[2*n+1] = BORDER + cy * TILE_SIZE;
5325 coords[2*n+0] -= dx * inset;
5326 coords[2*n+1] -= dy * inset;
5329 * We turned right, so inset this corner back along
5330 * the edge towards the centre of the square.
5332 coords[2*n+0] -= dy * inset;
5333 coords[2*n+1] += dx * inset;
5334 } else if (nin == 2) {
5336 * We turned left, so inset this corner further
5337 * _out_ along the edge into the next square.
5339 coords[2*n+0] += dy * inset;
5340 coords[2*n+1] -= dx * inset;
5344 } while (x != sx || y != sy || dx != sdx || dy != sdy);
5347 * That's our polygon; now draw it.
5349 draw_polygon(dr, coords, n, -1, ink);
5355 static void game_print(drawing *dr, game_state *state, int tilesize)
5358 int ink = print_mono_colour(dr, 0);
5361 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
5362 game_drawstate ads, *ds = &ads;
5363 game_set_size(dr, ds, NULL, tilesize);
5368 print_line_width(dr, 3 * TILE_SIZE / 40);
5369 draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
5372 * Highlight X-diagonal squares.
5376 int xhighlight = print_grey_colour(dr, 0.90F);
5378 for (i = 0; i < cr; i++)
5379 draw_rect(dr, BORDER + i*TILE_SIZE, BORDER + i*TILE_SIZE,
5380 TILE_SIZE, TILE_SIZE, xhighlight);
5381 for (i = 0; i < cr; i++)
5382 if (i*2 != cr-1) /* avoid redoing centre square, just for fun */
5383 draw_rect(dr, BORDER + i*TILE_SIZE,
5384 BORDER + (cr-1-i)*TILE_SIZE,
5385 TILE_SIZE, TILE_SIZE, xhighlight);
5391 for (x = 1; x < cr; x++) {
5392 print_line_width(dr, TILE_SIZE / 40);
5393 draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
5394 BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
5396 for (y = 1; y < cr; y++) {
5397 print_line_width(dr, TILE_SIZE / 40);
5398 draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
5399 BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
5403 * Thick lines between cells.
5405 print_line_width(dr, 3 * TILE_SIZE / 40);
5406 outline_block_structure(dr, ds, state, state->blocks, ink, 0);
5409 * Killer cages and their totals.
5411 if (state->kblocks) {
5412 print_line_width(dr, TILE_SIZE / 40);
5413 print_line_dotted(dr, TRUE);
5414 outline_block_structure(dr, ds, state, state->kblocks, ink,
5415 5 * TILE_SIZE / 40);
5416 print_line_dotted(dr, FALSE);
5417 for (y = 0; y < cr; y++)
5418 for (x = 0; x < cr; x++)
5419 if (state->kgrid[y*cr+x]) {
5421 sprintf(str, "%d", state->kgrid[y*cr+x]);
5423 BORDER+x*TILE_SIZE + 7*TILE_SIZE/40,
5424 BORDER+y*TILE_SIZE + 16*TILE_SIZE/40,
5425 FONT_VARIABLE, TILE_SIZE/4,
5426 ALIGN_VNORMAL | ALIGN_HLEFT,
5432 * Standard (non-Killer) clue numbers.
5434 for (y = 0; y < cr; y++)
5435 for (x = 0; x < cr; x++)
5436 if (state->grid[y*cr+x]) {
5439 str[0] = state->grid[y*cr+x] + '0';
5441 str[0] += 'a' - ('9'+1);
5442 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
5443 BORDER + y*TILE_SIZE + TILE_SIZE/2,
5444 FONT_VARIABLE, TILE_SIZE/2,
5445 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
5450 #define thegame solo
5453 const struct game thegame = {
5454 "Solo", "games.solo", "solo",
5461 TRUE, game_configure, custom_params,
5469 TRUE, game_can_format_as_text_now, game_text_format,
5477 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
5480 game_free_drawstate,
5484 TRUE, FALSE, game_print_size, game_print,
5485 FALSE, /* wants_statusbar */
5486 FALSE, game_timing_state,
5487 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
5490 #ifdef STANDALONE_SOLVER
5492 int main(int argc, char **argv)
5496 char *id = NULL, *desc, *err;
5498 struct difficulty dlev;
5500 while (--argc > 0) {
5502 if (!strcmp(p, "-v")) {
5503 solver_show_working = TRUE;
5504 } else if (!strcmp(p, "-g")) {
5506 } else if (*p == '-') {
5507 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
5515 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
5519 desc = strchr(id, ':');
5521 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
5526 p = default_params();
5527 decode_params(p, id);
5528 err = validate_desc(p, desc);
5530 fprintf(stderr, "%s: %s\n", argv[0], err);
5533 s = new_game(NULL, p, desc);
5535 dlev.maxdiff = DIFF_RECURSIVE;
5536 dlev.maxkdiff = DIFF_KINTERSECT;
5537 solver(s->cr, s->blocks, s->kblocks, s->xtype, s->grid, s->kgrid, &dlev);
5539 printf("Difficulty rating: %s\n",
5540 dlev.diff==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
5541 dlev.diff==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
5542 dlev.diff==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
5543 dlev.diff==DIFF_SET ? "Advanced (set elimination required)":
5544 dlev.diff==DIFF_EXTREME ? "Extreme (complex non-recursive techniques required)":
5545 dlev.diff==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
5546 dlev.diff==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
5547 dlev.diff==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
5548 "INTERNAL ERROR: unrecognised difficulty code");
5550 printf("Killer diffculty: %s\n",
5551 dlev.kdiff==DIFF_KSINGLE ? "Trivial (single square cages only)":
5552 dlev.kdiff==DIFF_KMINMAX ? "Simple (maximum sum analysis required)":
5553 dlev.kdiff==DIFF_KSUMS ? "Intermediate (sum possibilities)":
5554 dlev.kdiff==DIFF_KINTERSECT ? "Advanced (sum region intersections)":
5555 "INTERNAL ERROR: unrecognised difficulty code");
5557 printf("%s\n", grid_text_format(s->cr, s->blocks, s->xtype, s->grid));
5565 /* vim: set shiftwidth=4 tabstop=8: */