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 memcpy(nb
->blocknames
, b
->blocknames
, b
->c
* b
->r
*(sizeof(char *)+80));
588 for (i
= 0; i
< b
->c
* b
->r
; i
++)
589 if (b
->blocknames
[i
] == NULL
)
590 nb
->blocknames
[i
] = NULL
;
592 nb
->blocknames
[i
] = ((char *)nb
->blocknames
) + (b
->blocknames
[i
] - (char *)b
->blocknames
);
598 static void split_block(struct block_structure
*b
, int *squares
, int nr_squares
)
601 int previous_block
= b
->whichblock
[squares
[0]];
602 int newblock
= b
->nr_blocks
;
604 assert(b
->max_nr_squares
>= nr_squares
);
605 assert(b
->nr_squares
[previous_block
] > nr_squares
);
608 b
->blocks_data
= sresize(b
->blocks_data
,
609 b
->nr_blocks
* b
->max_nr_squares
, int);
610 b
->nr_squares
= sresize(b
->nr_squares
, b
->nr_blocks
, int);
612 b
->blocks
= snewn(b
->nr_blocks
, int *);
613 for (i
= 0; i
< b
->nr_blocks
; i
++)
614 b
->blocks
[i
] = b
->blocks_data
+ i
*b
->max_nr_squares
;
615 for (i
= 0; i
< nr_squares
; i
++) {
616 assert(b
->whichblock
[squares
[i
]] == previous_block
);
617 b
->whichblock
[squares
[i
]] = newblock
;
618 b
->blocks
[newblock
][i
] = squares
[i
];
620 for (i
= j
= 0; i
< b
->nr_squares
[previous_block
]; i
++) {
622 int sq
= b
->blocks
[previous_block
][i
];
623 for (k
= 0; k
< nr_squares
; k
++)
624 if (squares
[k
] == sq
)
627 b
->blocks
[previous_block
][j
++] = sq
;
629 b
->nr_squares
[previous_block
] -= nr_squares
;
630 b
->nr_squares
[newblock
] = nr_squares
;
633 static void remove_from_block(struct block_structure
*blocks
, int b
, int n
)
636 blocks
->whichblock
[n
] = -1;
637 for (i
= j
= 0; i
< blocks
->nr_squares
[b
]; i
++)
638 if (blocks
->blocks
[b
][i
] != n
)
639 blocks
->blocks
[b
][j
++] = blocks
->blocks
[b
][i
];
641 blocks
->nr_squares
[b
]--;
644 /* ----------------------------------------------------------------------
647 * This solver is used for two purposes:
648 * + to check solubility of a grid as we gradually remove numbers
650 * + to solve an externally generated puzzle when the user selects
653 * It supports a variety of specific modes of reasoning. By
654 * enabling or disabling subsets of these modes we can arrange a
655 * range of difficulty levels.
659 * Modes of reasoning currently supported:
661 * - Positional elimination: a number must go in a particular
662 * square because all the other empty squares in a given
663 * row/col/blk are ruled out.
665 * - Killer minmax elimination: for killer-type puzzles, a number
666 * is impossible if choosing it would cause the sum in a killer
667 * region to be guaranteed to be too large or too small.
669 * - Numeric elimination: a square must have a particular number
670 * in because all the other numbers that could go in it are
673 * - Intersectional analysis: given two domains which overlap
674 * (hence one must be a block, and the other can be a row or
675 * col), if the possible locations for a particular number in
676 * one of the domains can be narrowed down to the overlap, then
677 * that number can be ruled out everywhere but the overlap in
678 * the other domain too.
680 * - Set elimination: if there is a subset of the empty squares
681 * within a domain such that the union of the possible numbers
682 * in that subset has the same size as the subset itself, then
683 * those numbers can be ruled out everywhere else in the domain.
684 * (For example, if there are five empty squares and the
685 * possible numbers in each are 12, 23, 13, 134 and 1345, then
686 * the first three empty squares form such a subset: the numbers
687 * 1, 2 and 3 _must_ be in those three squares in some
688 * permutation, and hence we can deduce none of them can be in
689 * the fourth or fifth squares.)
690 * + You can also see this the other way round, concentrating
691 * on numbers rather than squares: if there is a subset of
692 * the unplaced numbers within a domain such that the union
693 * of all their possible positions has the same size as the
694 * subset itself, then all other numbers can be ruled out for
695 * those positions. However, it turns out that this is
696 * exactly equivalent to the first formulation at all times:
697 * there is a 1-1 correspondence between suitable subsets of
698 * the unplaced numbers and suitable subsets of the unfilled
699 * places, found by taking the _complement_ of the union of
700 * the numbers' possible positions (or the spaces' possible
703 * - Forcing chains (see comment for solver_forcing().)
705 * - Recursion. If all else fails, we pick one of the currently
706 * most constrained empty squares and take a random guess at its
707 * contents, then continue solving on that basis and see if we
711 struct solver_usage
{
713 struct block_structure
*blocks
, *kblocks
, *extra_cages
;
715 * We set up a cubic array, indexed by x, y and digit; each
716 * element of this array is TRUE or FALSE according to whether
717 * or not that digit _could_ in principle go in that position.
719 * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
720 * are macros below to help with this.
724 * This is the grid in which we write down our final
725 * deductions. y-coordinates in here are _not_ transformed.
729 * For killer-type puzzles, kclues holds the secondary clue for
730 * each cage. For derived cages, the clue is in extra_clues.
732 digit
*kclues
, *extra_clues
;
734 * Now we keep track, at a slightly higher level, of what we
735 * have yet to work out, to prevent doing the same deduction
738 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
740 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
742 /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
744 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
745 unsigned char *diag
; /* diag 0 is \, 1 is / */
751 #define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
752 #define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
753 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
754 #define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
756 #define ondiag0(xy) ((xy) % (cr+1) == 0)
757 #define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
758 #define diag0(i) ((i) * (cr+1))
759 #define diag1(i) ((i+1) * (cr-1))
762 * Function called when we are certain that a particular square has
763 * a particular number in it. The y-coordinate passed in here is
766 static void solver_place(struct solver_usage
*usage
, int x
, int y
, int n
)
769 int sqindex
= y
*cr
+x
;
775 * Rule out all other numbers in this square.
777 for (i
= 1; i
<= cr
; i
++)
782 * Rule out this number in all other positions in the row.
784 for (i
= 0; i
< cr
; i
++)
789 * Rule out this number in all other positions in the column.
791 for (i
= 0; i
< cr
; i
++)
796 * Rule out this number in all other positions in the block.
798 bi
= usage
->blocks
->whichblock
[sqindex
];
799 for (i
= 0; i
< cr
; i
++) {
800 int bp
= usage
->blocks
->blocks
[bi
][i
];
806 * Enter the number in the result grid.
808 usage
->grid
[sqindex
] = n
;
811 * Cross out this number from the list of numbers left to place
812 * in its row, its column and its block.
814 usage
->row
[y
*cr
+n
-1] = usage
->col
[x
*cr
+n
-1] =
815 usage
->blk
[bi
*cr
+n
-1] = TRUE
;
818 if (ondiag0(sqindex
)) {
819 for (i
= 0; i
< cr
; i
++)
820 if (diag0(i
) != sqindex
)
821 cube2(diag0(i
),n
) = FALSE
;
822 usage
->diag
[n
-1] = TRUE
;
824 if (ondiag1(sqindex
)) {
825 for (i
= 0; i
< cr
; i
++)
826 if (diag1(i
) != sqindex
)
827 cube2(diag1(i
),n
) = FALSE
;
828 usage
->diag
[cr
+n
-1] = TRUE
;
833 #if defined STANDALONE_SOLVER && defined __GNUC__
835 * Forward-declare the functions taking printf-like format arguments
836 * with __attribute__((format)) so as to ensure the argument syntax
839 struct solver_scratch
;
840 static int solver_elim(struct solver_usage
*usage
, int *indices
,
841 char *fmt
, ...) __attribute__((format(printf
,3,4)));
842 static int solver_intersect(struct solver_usage
*usage
,
843 int *indices1
, int *indices2
, char *fmt
, ...)
844 __attribute__((format(printf
,4,5)));
845 static int solver_set(struct solver_usage
*usage
,
846 struct solver_scratch
*scratch
,
847 int *indices
, char *fmt
, ...)
848 __attribute__((format(printf
,4,5)));
851 static int solver_elim(struct solver_usage
*usage
, int *indices
852 #ifdef STANDALONE_SOLVER
861 * Count the number of set bits within this section of the
866 for (i
= 0; i
< cr
; i
++)
867 if (usage
->cube
[indices
[i
]]) {
881 if (!usage
->grid
[y
*cr
+x
]) {
882 #ifdef STANDALONE_SOLVER
883 if (solver_show_working
) {
885 printf("%*s", solver_recurse_depth
*4, "");
889 printf(":\n%*s placing %d at (%d,%d)\n",
890 solver_recurse_depth
*4, "", n
, 1+x
, 1+y
);
893 solver_place(usage
, x
, y
, n
);
897 #ifdef STANDALONE_SOLVER
898 if (solver_show_working
) {
900 printf("%*s", solver_recurse_depth
*4, "");
904 printf(":\n%*s no possibilities available\n",
905 solver_recurse_depth
*4, "");
914 static int solver_intersect(struct solver_usage
*usage
,
915 int *indices1
, int *indices2
916 #ifdef STANDALONE_SOLVER
925 * Loop over the first domain and see if there's any set bit
926 * not also in the second.
928 for (i
= j
= 0; i
< cr
; i
++) {
930 while (j
< cr
&& indices2
[j
] < p
)
932 if (usage
->cube
[p
]) {
933 if (j
< cr
&& indices2
[j
] == p
)
934 continue; /* both domains contain this index */
936 return 0; /* there is, so we can't deduce */
941 * We have determined that all set bits in the first domain are
942 * within its overlap with the second. So loop over the second
943 * domain and remove all set bits that aren't also in that
944 * overlap; return +1 iff we actually _did_ anything.
947 for (i
= j
= 0; i
< cr
; i
++) {
949 while (j
< cr
&& indices1
[j
] < p
)
951 if (usage
->cube
[p
] && (j
>= cr
|| indices1
[j
] != p
)) {
952 #ifdef STANDALONE_SOLVER
953 if (solver_show_working
) {
958 printf("%*s", solver_recurse_depth
*4, "");
970 printf("%*s ruling out %d at (%d,%d)\n",
971 solver_recurse_depth
*4, "", pn
, 1+px
, 1+py
);
974 ret
= +1; /* we did something */
982 struct solver_scratch
{
983 unsigned char *grid
, *rowidx
, *colidx
, *set
;
984 int *neighbours
, *bfsqueue
;
985 int *indexlist
, *indexlist2
;
986 #ifdef STANDALONE_SOLVER
991 static int solver_set(struct solver_usage
*usage
,
992 struct solver_scratch
*scratch
,
994 #ifdef STANDALONE_SOLVER
1001 unsigned char *grid
= scratch
->grid
;
1002 unsigned char *rowidx
= scratch
->rowidx
;
1003 unsigned char *colidx
= scratch
->colidx
;
1004 unsigned char *set
= scratch
->set
;
1007 * We are passed a cr-by-cr matrix of booleans. Our first job
1008 * is to winnow it by finding any definite placements - i.e.
1009 * any row with a solitary 1 - and discarding that row and the
1010 * column containing the 1.
1012 memset(rowidx
, TRUE
, cr
);
1013 memset(colidx
, TRUE
, cr
);
1014 for (i
= 0; i
< cr
; i
++) {
1015 int count
= 0, first
= -1;
1016 for (j
= 0; j
< cr
; j
++)
1017 if (usage
->cube
[indices
[i
*cr
+j
]])
1021 * If count == 0, then there's a row with no 1s at all and
1022 * the puzzle is internally inconsistent. However, we ought
1023 * to have caught this already during the simpler reasoning
1024 * methods, so we can safely fail an assertion if we reach
1029 rowidx
[i
] = colidx
[first
] = FALSE
;
1033 * Convert each of rowidx/colidx from a list of 0s and 1s to a
1034 * list of the indices of the 1s.
1036 for (i
= j
= 0; i
< cr
; i
++)
1040 for (i
= j
= 0; i
< cr
; i
++)
1046 * And create the smaller matrix.
1048 for (i
= 0; i
< n
; i
++)
1049 for (j
= 0; j
< n
; j
++)
1050 grid
[i
*cr
+j
] = usage
->cube
[indices
[rowidx
[i
]*cr
+colidx
[j
]]];
1053 * Having done that, we now have a matrix in which every row
1054 * has at least two 1s in. Now we search to see if we can find
1055 * a rectangle of zeroes (in the set-theoretic sense of
1056 * `rectangle', i.e. a subset of rows crossed with a subset of
1057 * columns) whose width and height add up to n.
1064 * We have a candidate set. If its size is <=1 or >=n-1
1065 * then we move on immediately.
1067 if (count
> 1 && count
< n
-1) {
1069 * The number of rows we need is n-count. See if we can
1070 * find that many rows which each have a zero in all
1071 * the positions listed in `set'.
1074 for (i
= 0; i
< n
; i
++) {
1076 for (j
= 0; j
< n
; j
++)
1077 if (set
[j
] && grid
[i
*cr
+j
]) {
1086 * We expect never to be able to get _more_ than
1087 * n-count suitable rows: this would imply that (for
1088 * example) there are four numbers which between them
1089 * have at most three possible positions, and hence it
1090 * indicates a faulty deduction before this point or
1091 * even a bogus clue.
1093 if (rows
> n
- count
) {
1094 #ifdef STANDALONE_SOLVER
1095 if (solver_show_working
) {
1097 printf("%*s", solver_recurse_depth
*4,
1102 printf(":\n%*s contradiction reached\n",
1103 solver_recurse_depth
*4, "");
1109 if (rows
>= n
- count
) {
1110 int progress
= FALSE
;
1113 * We've got one! Now, for each row which _doesn't_
1114 * satisfy the criterion, eliminate all its set
1115 * bits in the positions _not_ listed in `set'.
1116 * Return +1 (meaning progress has been made) if we
1117 * successfully eliminated anything at all.
1119 * This involves referring back through
1120 * rowidx/colidx in order to work out which actual
1121 * positions in the cube to meddle with.
1123 for (i
= 0; i
< n
; i
++) {
1125 for (j
= 0; j
< n
; j
++)
1126 if (set
[j
] && grid
[i
*cr
+j
]) {
1131 for (j
= 0; j
< n
; j
++)
1132 if (!set
[j
] && grid
[i
*cr
+j
]) {
1133 int fpos
= indices
[rowidx
[i
]*cr
+colidx
[j
]];
1134 #ifdef STANDALONE_SOLVER
1135 if (solver_show_working
) {
1140 printf("%*s", solver_recurse_depth
*4,
1153 printf("%*s ruling out %d at (%d,%d)\n",
1154 solver_recurse_depth
*4, "",
1159 usage
->cube
[fpos
] = FALSE
;
1171 * Binary increment: change the rightmost 0 to a 1, and
1172 * change all 1s to the right of it to 0s.
1175 while (i
> 0 && set
[i
-1])
1176 set
[--i
] = 0, count
--;
1178 set
[--i
] = 1, count
++;
1187 * Look for forcing chains. A forcing chain is a path of
1188 * pairwise-exclusive squares (i.e. each pair of adjacent squares
1189 * in the path are in the same row, column or block) with the
1190 * following properties:
1192 * (a) Each square on the path has precisely two possible numbers.
1194 * (b) Each pair of squares which are adjacent on the path share
1195 * at least one possible number in common.
1197 * (c) Each square in the middle of the path shares _both_ of its
1198 * numbers with at least one of its neighbours (not the same
1199 * one with both neighbours).
1201 * These together imply that at least one of the possible number
1202 * choices at one end of the path forces _all_ the rest of the
1203 * numbers along the path. In order to make real use of this, we
1204 * need further properties:
1206 * (c) Ruling out some number N from the square at one end of the
1207 * path forces the square at the other end to take the same
1210 * (d) The two end squares are both in line with some third
1213 * (e) That third square currently has N as a possibility.
1215 * If we can find all of that lot, we can deduce that at least one
1216 * of the two ends of the forcing chain has number N, and that
1217 * therefore the mutually adjacent third square does not.
1219 * To find forcing chains, we're going to start a bfs at each
1220 * suitable square, once for each of its two possible numbers.
1222 static int solver_forcing(struct solver_usage
*usage
,
1223 struct solver_scratch
*scratch
)
1226 int *bfsqueue
= scratch
->bfsqueue
;
1227 #ifdef STANDALONE_SOLVER
1228 int *bfsprev
= scratch
->bfsprev
;
1230 unsigned char *number
= scratch
->grid
;
1231 int *neighbours
= scratch
->neighbours
;
1234 for (y
= 0; y
< cr
; y
++)
1235 for (x
= 0; x
< cr
; x
++) {
1239 * If this square doesn't have exactly two candidate
1240 * numbers, don't try it.
1242 * In this loop we also sum the candidate numbers,
1243 * which is a nasty hack to allow us to quickly find
1244 * `the other one' (since we will shortly know there
1247 for (count
= t
= 0, n
= 1; n
<= cr
; n
++)
1254 * Now attempt a bfs for each candidate.
1256 for (n
= 1; n
<= cr
; n
++)
1257 if (cube(x
, y
, n
)) {
1258 int orign
, currn
, head
, tail
;
1265 memset(number
, cr
+1, cr
*cr
);
1267 bfsqueue
[tail
++] = y
*cr
+x
;
1268 #ifdef STANDALONE_SOLVER
1269 bfsprev
[y
*cr
+x
] = -1;
1271 number
[y
*cr
+x
] = t
- n
;
1273 while (head
< tail
) {
1274 int xx
, yy
, nneighbours
, xt
, yt
, i
;
1276 xx
= bfsqueue
[head
++];
1280 currn
= number
[yy
*cr
+xx
];
1283 * Find neighbours of yy,xx.
1286 for (yt
= 0; yt
< cr
; yt
++)
1287 neighbours
[nneighbours
++] = yt
*cr
+xx
;
1288 for (xt
= 0; xt
< cr
; xt
++)
1289 neighbours
[nneighbours
++] = yy
*cr
+xt
;
1290 xt
= usage
->blocks
->whichblock
[yy
*cr
+xx
];
1291 for (yt
= 0; yt
< cr
; yt
++)
1292 neighbours
[nneighbours
++] = usage
->blocks
->blocks
[xt
][yt
];
1294 int sqindex
= yy
*cr
+xx
;
1295 if (ondiag0(sqindex
)) {
1296 for (i
= 0; i
< cr
; i
++)
1297 neighbours
[nneighbours
++] = diag0(i
);
1299 if (ondiag1(sqindex
)) {
1300 for (i
= 0; i
< cr
; i
++)
1301 neighbours
[nneighbours
++] = diag1(i
);
1306 * Try visiting each of those neighbours.
1308 for (i
= 0; i
< nneighbours
; i
++) {
1311 xt
= neighbours
[i
] % cr
;
1312 yt
= neighbours
[i
] / cr
;
1315 * We need this square to not be
1316 * already visited, and to include
1317 * currn as a possible number.
1319 if (number
[yt
*cr
+xt
] <= cr
)
1321 if (!cube(xt
, yt
, currn
))
1325 * Don't visit _this_ square a second
1328 if (xt
== xx
&& yt
== yy
)
1332 * To continue with the bfs, we need
1333 * this square to have exactly two
1336 for (cc
= tt
= 0, nn
= 1; nn
<= cr
; nn
++)
1337 if (cube(xt
, yt
, nn
))
1340 bfsqueue
[tail
++] = yt
*cr
+xt
;
1341 #ifdef STANDALONE_SOLVER
1342 bfsprev
[yt
*cr
+xt
] = yy
*cr
+xx
;
1344 number
[yt
*cr
+xt
] = tt
- currn
;
1348 * One other possibility is that this
1349 * might be the square in which we can
1350 * make a real deduction: if it's
1351 * adjacent to x,y, and currn is equal
1352 * to the original number we ruled out.
1354 if (currn
== orign
&&
1355 (xt
== x
|| yt
== y
||
1356 (usage
->blocks
->whichblock
[yt
*cr
+xt
] == usage
->blocks
->whichblock
[y
*cr
+x
]) ||
1357 (usage
->diag
&& ((ondiag0(yt
*cr
+xt
) && ondiag0(y
*cr
+x
)) ||
1358 (ondiag1(yt
*cr
+xt
) && ondiag1(y
*cr
+x
)))))) {
1359 #ifdef STANDALONE_SOLVER
1360 if (solver_show_working
) {
1363 printf("%*sforcing chain, %d at ends of ",
1364 solver_recurse_depth
*4, "", orign
);
1368 printf("%s(%d,%d)", sep
, 1+xl
,
1370 xl
= bfsprev
[yl
*cr
+xl
];
1377 printf("\n%*s ruling out %d at (%d,%d)\n",
1378 solver_recurse_depth
*4, "",
1382 cube(xt
, yt
, orign
) = FALSE
;
1393 static int solver_killer_minmax(struct solver_usage
*usage
,
1394 struct block_structure
*cages
, digit
*clues
,
1396 #ifdef STANDALONE_SOLVER
1404 int nsquares
= cages
->nr_squares
[b
];
1409 for (i
= 0; i
< nsquares
; i
++) {
1410 int n
, x
= cages
->blocks
[b
][i
];
1412 for (n
= 1; n
<= cr
; n
++)
1414 int maxval
= 0, minval
= 0;
1416 for (j
= 0; j
< nsquares
; j
++) {
1418 int y
= cages
->blocks
[b
][j
];
1421 for (m
= 1; m
<= cr
; m
++)
1426 for (m
= cr
; m
> 0; m
--)
1432 if (maxval
+ n
< clues
[b
]) {
1433 cube2(x
, n
) = FALSE
;
1435 #ifdef STANDALONE_SOLVER
1436 if (solver_show_working
)
1437 printf("%*s ruling out %d at (%d,%d) as too low %s\n",
1438 solver_recurse_depth
*4, "killer minmax analysis",
1439 n
, 1 + x
%cr
, 1 + x
/cr
, extra
);
1442 if (minval
+ n
> clues
[b
]) {
1443 cube2(x
, n
) = FALSE
;
1445 #ifdef STANDALONE_SOLVER
1446 if (solver_show_working
)
1447 printf("%*s ruling out %d at (%d,%d) as too high %s\n",
1448 solver_recurse_depth
*4, "killer minmax analysis",
1449 n
, 1 + x
%cr
, 1 + x
/cr
, extra
);
1457 static int solver_killer_sums(struct solver_usage
*usage
, int b
,
1458 struct block_structure
*cages
, int clue
,
1460 #ifdef STANDALONE_SOLVER
1461 , const char *cage_type
1466 int i
, ret
, max_sums
;
1467 int nsquares
= cages
->nr_squares
[b
];
1468 unsigned long *sumbits
, possible_addends
;
1471 assert(nsquares
== 0);
1474 assert(nsquares
> 0);
1476 if (nsquares
< 2 || nsquares
> 4)
1479 if (!cage_is_region
) {
1480 int known_row
= -1, known_col
= -1, known_block
= -1;
1482 * Verify that the cage lies entirely within one region,
1483 * so that using the precomputed sums is valid.
1485 for (i
= 0; i
< nsquares
; i
++) {
1486 int x
= cages
->blocks
[b
][i
];
1488 assert(usage
->grid
[x
] == 0);
1493 known_block
= usage
->blocks
->whichblock
[x
];
1495 if (known_row
!= x
/cr
)
1497 if (known_col
!= x
%cr
)
1499 if (known_block
!= usage
->blocks
->whichblock
[x
])
1503 if (known_block
== -1 && known_col
== -1 && known_row
== -1)
1506 if (nsquares
== 2) {
1507 if (clue
< 3 || clue
> 17)
1510 sumbits
= sum_bits2
[clue
];
1511 max_sums
= MAX_2SUMS
;
1512 } else if (nsquares
== 3) {
1513 if (clue
< 6 || clue
> 24)
1516 sumbits
= sum_bits3
[clue
];
1517 max_sums
= MAX_3SUMS
;
1519 if (clue
< 10 || clue
> 30)
1522 sumbits
= sum_bits4
[clue
];
1523 max_sums
= MAX_4SUMS
;
1526 * For every possible way to get the sum, see if there is
1527 * one square in the cage that disallows all the required
1528 * addends. If we find one such square, this way to compute
1529 * the sum is impossible.
1531 possible_addends
= 0;
1532 for (i
= 0; i
< max_sums
; i
++) {
1534 unsigned long bits
= sumbits
[i
];
1539 for (j
= 0; j
< nsquares
; j
++) {
1541 unsigned long square_bits
= bits
;
1542 int x
= cages
->blocks
[b
][j
];
1543 for (n
= 1; n
<= cr
; n
++)
1545 square_bits
&= ~(1L << n
);
1546 if (square_bits
== 0) {
1551 possible_addends
|= bits
;
1554 * Now we know which addends can possibly be used to
1555 * compute the sum. Remove all other digits from the
1556 * set of possibilities.
1558 if (possible_addends
== 0)
1562 for (i
= 0; i
< nsquares
; i
++) {
1564 int x
= cages
->blocks
[b
][i
];
1565 for (n
= 1; n
<= cr
; n
++) {
1568 if ((possible_addends
& (1 << n
)) == 0) {
1569 cube2(x
, n
) = FALSE
;
1571 #ifdef STANDALONE_SOLVER
1572 if (solver_show_working
) {
1573 printf("%*s using %s\n",
1574 solver_recurse_depth
*4, "killer sums analysis",
1576 printf("%*s ruling out %d at (%d,%d) due to impossible %d-sum\n",
1577 solver_recurse_depth
*4, "",
1578 n
, 1 + x
%cr
, 1 + x
/cr
, nsquares
);
1587 static int filter_whole_cages(struct solver_usage
*usage
, int *squares
, int n
,
1593 /* First, filter squares with a clue. */
1594 for (i
= j
= 0; i
< n
; i
++)
1595 if (usage
->grid
[squares
[i
]])
1596 *filtered_sum
+= usage
->grid
[squares
[i
]];
1598 squares
[j
++] = squares
[i
];
1602 * Filter all cages that are covered entirely by the list of
1606 for (b
= 0; b
< usage
->kblocks
->nr_blocks
&& off
< n
; b
++) {
1607 int b_squares
= usage
->kblocks
->nr_squares
[b
];
1614 * Find all squares of block b that lie in our list,
1615 * and make them contiguous at off, which is the current position
1616 * in the output list.
1618 for (i
= 0; i
< b_squares
; i
++) {
1619 for (j
= off
; j
< n
; j
++)
1620 if (squares
[j
] == usage
->kblocks
->blocks
[b
][i
]) {
1621 int t
= squares
[off
+ matched
];
1622 squares
[off
+ matched
] = squares
[j
];
1628 /* If so, filter out all squares of b from the list. */
1629 if (matched
!= usage
->kblocks
->nr_squares
[b
]) {
1633 memmove(squares
+ off
, squares
+ off
+ matched
,
1634 (n
- off
- matched
) * sizeof *squares
);
1637 *filtered_sum
+= usage
->kclues
[b
];
1643 static struct solver_scratch
*solver_new_scratch(struct solver_usage
*usage
)
1645 struct solver_scratch
*scratch
= snew(struct solver_scratch
);
1647 scratch
->grid
= snewn(cr
*cr
, unsigned char);
1648 scratch
->rowidx
= snewn(cr
, unsigned char);
1649 scratch
->colidx
= snewn(cr
, unsigned char);
1650 scratch
->set
= snewn(cr
, unsigned char);
1651 scratch
->neighbours
= snewn(5*cr
, int);
1652 scratch
->bfsqueue
= snewn(cr
*cr
, int);
1653 #ifdef STANDALONE_SOLVER
1654 scratch
->bfsprev
= snewn(cr
*cr
, int);
1656 scratch
->indexlist
= snewn(cr
*cr
, int); /* used for set elimination */
1657 scratch
->indexlist2
= snewn(cr
, int); /* only used for intersect() */
1661 static void solver_free_scratch(struct solver_scratch
*scratch
)
1663 #ifdef STANDALONE_SOLVER
1664 sfree(scratch
->bfsprev
);
1666 sfree(scratch
->bfsqueue
);
1667 sfree(scratch
->neighbours
);
1668 sfree(scratch
->set
);
1669 sfree(scratch
->colidx
);
1670 sfree(scratch
->rowidx
);
1671 sfree(scratch
->grid
);
1672 sfree(scratch
->indexlist
);
1673 sfree(scratch
->indexlist2
);
1678 * Used for passing information about difficulty levels between the solver
1682 /* Maximum levels allowed. */
1683 int maxdiff
, maxkdiff
;
1684 /* Levels reached by the solver. */
1688 static void solver(int cr
, struct block_structure
*blocks
,
1689 struct block_structure
*kblocks
, int xtype
,
1690 digit
*grid
, digit
*kgrid
, struct difficulty
*dlev
)
1692 struct solver_usage
*usage
;
1693 struct solver_scratch
*scratch
;
1694 int x
, y
, b
, i
, n
, ret
;
1695 int diff
= DIFF_BLOCK
;
1696 int kdiff
= DIFF_KSINGLE
;
1699 * Set up a usage structure as a clean slate (everything
1702 usage
= snew(struct solver_usage
);
1704 usage
->blocks
= blocks
;
1706 usage
->kblocks
= dup_block_structure(kblocks
);
1707 usage
->extra_cages
= alloc_block_structure (kblocks
->c
, kblocks
->r
,
1708 cr
* cr
, cr
, cr
* cr
);
1709 usage
->extra_clues
= snewn(cr
*cr
, digit
);
1711 usage
->kblocks
= usage
->extra_cages
= NULL
;
1712 usage
->extra_clues
= NULL
;
1714 usage
->cube
= snewn(cr
*cr
*cr
, unsigned char);
1715 usage
->grid
= grid
; /* write straight back to the input */
1720 nclues
= kblocks
->nr_blocks
;
1722 * Allow for expansion of the killer regions, the absolute
1723 * limit is obviously one region per square.
1725 usage
->kclues
= snewn(cr
*cr
, digit
);
1726 for (i
= 0; i
< nclues
; i
++) {
1727 for (n
= 0; n
< kblocks
->nr_squares
[i
]; n
++)
1728 if (kgrid
[kblocks
->blocks
[i
][n
]] != 0)
1729 usage
->kclues
[i
] = kgrid
[kblocks
->blocks
[i
][n
]];
1730 assert(usage
->kclues
[i
] > 0);
1732 memset(usage
->kclues
+ nclues
, 0, cr
*cr
- nclues
);
1734 usage
->kclues
= NULL
;
1737 memset(usage
->cube
, TRUE
, cr
*cr
*cr
);
1739 usage
->row
= snewn(cr
* cr
, unsigned char);
1740 usage
->col
= snewn(cr
* cr
, unsigned char);
1741 usage
->blk
= snewn(cr
* cr
, unsigned char);
1742 memset(usage
->row
, FALSE
, cr
* cr
);
1743 memset(usage
->col
, FALSE
, cr
* cr
);
1744 memset(usage
->blk
, FALSE
, cr
* cr
);
1747 usage
->diag
= snewn(cr
* 2, unsigned char);
1748 memset(usage
->diag
, FALSE
, cr
* 2);
1752 usage
->nr_regions
= cr
* 3 + (xtype
? 2 : 0);
1753 usage
->regions
= snewn(cr
* usage
->nr_regions
, int);
1754 usage
->sq2region
= snewn(cr
* cr
* 3, int *);
1756 for (n
= 0; n
< cr
; n
++) {
1757 for (i
= 0; i
< cr
; i
++) {
1760 b
= usage
->blocks
->blocks
[n
][i
];
1761 usage
->regions
[cr
*n
*3 + i
] = x
;
1762 usage
->regions
[cr
*n
*3 + cr
+ i
] = y
;
1763 usage
->regions
[cr
*n
*3 + 2*cr
+ i
] = b
;
1764 usage
->sq2region
[x
*3] = usage
->regions
+ cr
*n
*3;
1765 usage
->sq2region
[y
*3 + 1] = usage
->regions
+ cr
*n
*3 + cr
;
1766 usage
->sq2region
[b
*3 + 2] = usage
->regions
+ cr
*n
*3 + 2*cr
;
1770 scratch
= solver_new_scratch(usage
);
1773 * Place all the clue numbers we are given.
1775 for (x
= 0; x
< cr
; x
++)
1776 for (y
= 0; y
< cr
; y
++)
1778 solver_place(usage
, x
, y
, grid
[y
*cr
+x
]);
1781 * Now loop over the grid repeatedly trying all permitted modes
1782 * of reasoning. The loop terminates if we complete an
1783 * iteration without making any progress; we then return
1784 * failure or success depending on whether the grid is full or
1789 * I'd like to write `continue;' inside each of the
1790 * following loops, so that the solver returns here after
1791 * making some progress. However, I can't specify that I
1792 * want to continue an outer loop rather than the innermost
1793 * one, so I'm apologetically resorting to a goto.
1798 * Blockwise positional elimination.
1800 for (b
= 0; b
< cr
; b
++)
1801 for (n
= 1; n
<= cr
; n
++)
1802 if (!usage
->blk
[b
*cr
+n
-1]) {
1803 for (i
= 0; i
< cr
; i
++)
1804 scratch
->indexlist
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
],n
);
1805 ret
= solver_elim(usage
, scratch
->indexlist
1806 #ifdef STANDALONE_SOLVER
1807 , "positional elimination,"
1808 " %d in block %s", n
,
1809 usage
->blocks
->blocknames
[b
]
1813 diff
= DIFF_IMPOSSIBLE
;
1815 } else if (ret
> 0) {
1816 diff
= max(diff
, DIFF_BLOCK
);
1821 if (usage
->kclues
!= NULL
) {
1822 int changed
= FALSE
;
1825 * First, bring the kblocks into a more useful form: remove
1826 * all filled-in squares, and reduce the sum by their values.
1827 * Walk in reverse order, since otherwise remove_from_block
1828 * can move element past our loop counter.
1830 for (b
= 0; b
< usage
->kblocks
->nr_blocks
; b
++)
1831 for (i
= usage
->kblocks
->nr_squares
[b
] -1; i
>= 0; i
--) {
1832 int x
= usage
->kblocks
->blocks
[b
][i
];
1833 int t
= usage
->grid
[x
];
1837 remove_from_block(usage
->kblocks
, b
, x
);
1838 if (t
> usage
->kclues
[b
]) {
1839 diff
= DIFF_IMPOSSIBLE
;
1842 usage
->kclues
[b
] -= t
;
1844 * Since cages are regions, this tells us something
1845 * about the other squares in the cage.
1847 for (n
= 0; n
< usage
->kblocks
->nr_squares
[b
]; n
++) {
1848 cube2(usage
->kblocks
->blocks
[b
][n
], t
) = FALSE
;
1853 * The most trivial kind of solver for killer puzzles: fill
1854 * single-square cages.
1856 for (b
= 0; b
< usage
->kblocks
->nr_blocks
; b
++) {
1857 int squares
= usage
->kblocks
->nr_squares
[b
];
1859 int v
= usage
->kclues
[b
];
1860 if (v
< 1 || v
> cr
) {
1861 diff
= DIFF_IMPOSSIBLE
;
1864 x
= usage
->kblocks
->blocks
[b
][0] % cr
;
1865 y
= usage
->kblocks
->blocks
[b
][0] / cr
;
1866 if (!cube(x
, y
, v
)) {
1867 diff
= DIFF_IMPOSSIBLE
;
1870 solver_place(usage
, x
, y
, v
);
1872 #ifdef STANDALONE_SOLVER
1873 if (solver_show_working
) {
1874 printf("%*s placing %d at (%d,%d)\n",
1875 solver_recurse_depth
*4, "killer single-square cage",
1876 v
, 1 + x
%cr
, 1 + x
/cr
);
1884 kdiff
= max(kdiff
, DIFF_KSINGLE
);
1888 if (dlev
->maxkdiff
>= DIFF_KINTERSECT
&& usage
->kclues
!= NULL
) {
1889 int changed
= FALSE
;
1891 * Now, create the extra_cages information. Every full region
1892 * (row, column, or block) has the same sum total (45 for 3x3
1893 * puzzles. After we try to cover these regions with cages that
1894 * lie entirely within them, any squares that remain must bring
1895 * the total to this known value, and so they form additional
1896 * cages which aren't immediately evident in the displayed form
1899 usage
->extra_cages
->nr_blocks
= 0;
1900 for (i
= 0; i
< 3; i
++) {
1901 for (n
= 0; n
< cr
; n
++) {
1902 int *region
= usage
->regions
+ cr
*n
*3 + i
*cr
;
1903 int sum
= cr
* (cr
+ 1) / 2;
1906 int n_extra
= usage
->extra_cages
->nr_blocks
;
1907 int *extra_list
= usage
->extra_cages
->blocks
[n_extra
];
1908 memcpy(extra_list
, region
, cr
* sizeof *extra_list
);
1910 nsquares
= filter_whole_cages(usage
, extra_list
, nsquares
, &filtered
);
1912 if (nsquares
== cr
|| nsquares
== 0)
1914 if (dlev
->maxdiff
>= DIFF_RECURSIVE
) {
1916 dlev
->diff
= DIFF_IMPOSSIBLE
;
1922 if (nsquares
== 1) {
1924 diff
= DIFF_IMPOSSIBLE
;
1927 x
= extra_list
[0] % cr
;
1928 y
= extra_list
[0] / cr
;
1929 if (!cube(x
, y
, sum
)) {
1930 diff
= DIFF_IMPOSSIBLE
;
1933 solver_place(usage
, x
, y
, sum
);
1935 #ifdef STANDALONE_SOLVER
1936 if (solver_show_working
) {
1937 printf("%*s placing %d at (%d,%d)\n",
1938 solver_recurse_depth
*4, "killer single-square deduced cage",
1944 b
= usage
->kblocks
->whichblock
[extra_list
[0]];
1945 for (x
= 1; x
< nsquares
; x
++)
1946 if (usage
->kblocks
->whichblock
[extra_list
[x
]] != b
)
1948 if (x
== nsquares
) {
1949 assert(usage
->kblocks
->nr_squares
[b
] > nsquares
);
1950 split_block(usage
->kblocks
, extra_list
, nsquares
);
1951 assert(usage
->kblocks
->nr_squares
[usage
->kblocks
->nr_blocks
- 1] == nsquares
);
1952 usage
->kclues
[usage
->kblocks
->nr_blocks
- 1] = sum
;
1953 usage
->kclues
[b
] -= sum
;
1955 usage
->extra_cages
->nr_squares
[n_extra
] = nsquares
;
1956 usage
->extra_cages
->nr_blocks
++;
1957 usage
->extra_clues
[n_extra
] = sum
;
1962 kdiff
= max(kdiff
, DIFF_KINTERSECT
);
1968 * Another simple killer-type elimination. For every square in a
1969 * cage, find the minimum and maximum possible sums of all the
1970 * other squares in the same cage, and rule out possibilities
1971 * for the given square based on whether they are guaranteed to
1972 * cause the sum to be either too high or too low.
1973 * This is a special case of trying all possible sums across a
1974 * region, which is a recursive algorithm. We should probably
1975 * implement it for a higher difficulty level.
1977 if (dlev
->maxkdiff
>= DIFF_KMINMAX
&& usage
->kclues
!= NULL
) {
1978 int changed
= FALSE
;
1979 for (b
= 0; b
< usage
->kblocks
->nr_blocks
; b
++) {
1980 int ret
= solver_killer_minmax(usage
, usage
->kblocks
,
1982 #ifdef STANDALONE_SOLVER
1987 diff
= DIFF_IMPOSSIBLE
;
1992 for (b
= 0; b
< usage
->extra_cages
->nr_blocks
; b
++) {
1993 int ret
= solver_killer_minmax(usage
, usage
->extra_cages
,
1994 usage
->extra_clues
, b
1995 #ifdef STANDALONE_SOLVER
1996 , "using deduced cages"
2000 diff
= DIFF_IMPOSSIBLE
;
2006 kdiff
= max(kdiff
, DIFF_KMINMAX
);
2012 * Try to use knowledge of which numbers can be used to generate
2014 * This can only be used if a cage lies entirely within a region.
2016 if (dlev
->maxkdiff
>= DIFF_KSUMS
&& usage
->kclues
!= NULL
) {
2017 int changed
= FALSE
;
2019 for (b
= 0; b
< usage
->kblocks
->nr_blocks
; b
++) {
2020 int ret
= solver_killer_sums(usage
, b
, usage
->kblocks
,
2021 usage
->kclues
[b
], TRUE
2022 #ifdef STANDALONE_SOLVER
2028 kdiff
= max(kdiff
, DIFF_KSUMS
);
2029 } else if (ret
< 0) {
2030 diff
= DIFF_IMPOSSIBLE
;
2035 for (b
= 0; b
< usage
->extra_cages
->nr_blocks
; b
++) {
2036 int ret
= solver_killer_sums(usage
, b
, usage
->extra_cages
,
2037 usage
->extra_clues
[b
], FALSE
2038 #ifdef STANDALONE_SOLVER
2044 kdiff
= max(kdiff
, DIFF_KSUMS
);
2045 } else if (ret
< 0) {
2046 diff
= DIFF_IMPOSSIBLE
;
2055 if (dlev
->maxdiff
<= DIFF_BLOCK
)
2059 * Row-wise positional elimination.
2061 for (y
= 0; y
< cr
; y
++)
2062 for (n
= 1; n
<= cr
; n
++)
2063 if (!usage
->row
[y
*cr
+n
-1]) {
2064 for (x
= 0; x
< cr
; x
++)
2065 scratch
->indexlist
[x
] = cubepos(x
, y
, n
);
2066 ret
= solver_elim(usage
, scratch
->indexlist
2067 #ifdef STANDALONE_SOLVER
2068 , "positional elimination,"
2069 " %d in row %d", n
, 1+y
2073 diff
= DIFF_IMPOSSIBLE
;
2075 } else if (ret
> 0) {
2076 diff
= max(diff
, DIFF_SIMPLE
);
2081 * Column-wise positional elimination.
2083 for (x
= 0; x
< cr
; x
++)
2084 for (n
= 1; n
<= cr
; n
++)
2085 if (!usage
->col
[x
*cr
+n
-1]) {
2086 for (y
= 0; y
< cr
; y
++)
2087 scratch
->indexlist
[y
] = cubepos(x
, y
, n
);
2088 ret
= solver_elim(usage
, scratch
->indexlist
2089 #ifdef STANDALONE_SOLVER
2090 , "positional elimination,"
2091 " %d in column %d", n
, 1+x
2095 diff
= DIFF_IMPOSSIBLE
;
2097 } else if (ret
> 0) {
2098 diff
= max(diff
, DIFF_SIMPLE
);
2104 * X-diagonal positional elimination.
2107 for (n
= 1; n
<= cr
; n
++)
2108 if (!usage
->diag
[n
-1]) {
2109 for (i
= 0; i
< cr
; i
++)
2110 scratch
->indexlist
[i
] = cubepos2(diag0(i
), n
);
2111 ret
= solver_elim(usage
, scratch
->indexlist
2112 #ifdef STANDALONE_SOLVER
2113 , "positional elimination,"
2114 " %d in \\-diagonal", n
2118 diff
= DIFF_IMPOSSIBLE
;
2120 } else if (ret
> 0) {
2121 diff
= max(diff
, DIFF_SIMPLE
);
2125 for (n
= 1; n
<= cr
; n
++)
2126 if (!usage
->diag
[cr
+n
-1]) {
2127 for (i
= 0; i
< cr
; i
++)
2128 scratch
->indexlist
[i
] = cubepos2(diag1(i
), n
);
2129 ret
= solver_elim(usage
, scratch
->indexlist
2130 #ifdef STANDALONE_SOLVER
2131 , "positional elimination,"
2132 " %d in /-diagonal", n
2136 diff
= DIFF_IMPOSSIBLE
;
2138 } else if (ret
> 0) {
2139 diff
= max(diff
, DIFF_SIMPLE
);
2146 * Numeric elimination.
2148 for (x
= 0; x
< cr
; x
++)
2149 for (y
= 0; y
< cr
; y
++)
2150 if (!usage
->grid
[y
*cr
+x
]) {
2151 for (n
= 1; n
<= cr
; n
++)
2152 scratch
->indexlist
[n
-1] = cubepos(x
, y
, n
);
2153 ret
= solver_elim(usage
, scratch
->indexlist
2154 #ifdef STANDALONE_SOLVER
2155 , "numeric elimination at (%d,%d)",
2160 diff
= DIFF_IMPOSSIBLE
;
2162 } else if (ret
> 0) {
2163 diff
= max(diff
, DIFF_SIMPLE
);
2168 if (dlev
->maxdiff
<= DIFF_SIMPLE
)
2172 * Intersectional analysis, rows vs blocks.
2174 for (y
= 0; y
< cr
; y
++)
2175 for (b
= 0; b
< cr
; b
++)
2176 for (n
= 1; n
<= cr
; n
++) {
2177 if (usage
->row
[y
*cr
+n
-1] ||
2178 usage
->blk
[b
*cr
+n
-1])
2180 for (i
= 0; i
< cr
; i
++) {
2181 scratch
->indexlist
[i
] = cubepos(i
, y
, n
);
2182 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
2185 * solver_intersect() never returns -1.
2187 if (solver_intersect(usage
, scratch
->indexlist
,
2189 #ifdef STANDALONE_SOLVER
2190 , "intersectional analysis,"
2191 " %d in row %d vs block %s",
2192 n
, 1+y
, usage
->blocks
->blocknames
[b
]
2195 solver_intersect(usage
, scratch
->indexlist2
,
2197 #ifdef STANDALONE_SOLVER
2198 , "intersectional analysis,"
2199 " %d in block %s vs row %d",
2200 n
, usage
->blocks
->blocknames
[b
], 1+y
2203 diff
= max(diff
, DIFF_INTERSECT
);
2209 * Intersectional analysis, columns vs blocks.
2211 for (x
= 0; x
< cr
; x
++)
2212 for (b
= 0; b
< cr
; b
++)
2213 for (n
= 1; n
<= cr
; n
++) {
2214 if (usage
->col
[x
*cr
+n
-1] ||
2215 usage
->blk
[b
*cr
+n
-1])
2217 for (i
= 0; i
< cr
; i
++) {
2218 scratch
->indexlist
[i
] = cubepos(x
, i
, n
);
2219 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
2221 if (solver_intersect(usage
, scratch
->indexlist
,
2223 #ifdef STANDALONE_SOLVER
2224 , "intersectional analysis,"
2225 " %d in column %d vs block %s",
2226 n
, 1+x
, usage
->blocks
->blocknames
[b
]
2229 solver_intersect(usage
, scratch
->indexlist2
,
2231 #ifdef STANDALONE_SOLVER
2232 , "intersectional analysis,"
2233 " %d in block %s vs column %d",
2234 n
, usage
->blocks
->blocknames
[b
], 1+x
2237 diff
= max(diff
, DIFF_INTERSECT
);
2244 * Intersectional analysis, \-diagonal vs blocks.
2246 for (b
= 0; b
< cr
; b
++)
2247 for (n
= 1; n
<= cr
; n
++) {
2248 if (usage
->diag
[n
-1] ||
2249 usage
->blk
[b
*cr
+n
-1])
2251 for (i
= 0; i
< cr
; i
++) {
2252 scratch
->indexlist
[i
] = cubepos2(diag0(i
), n
);
2253 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
2255 if (solver_intersect(usage
, scratch
->indexlist
,
2257 #ifdef STANDALONE_SOLVER
2258 , "intersectional analysis,"
2259 " %d in \\-diagonal vs block %s",
2260 n
, usage
->blocks
->blocknames
[b
]
2263 solver_intersect(usage
, scratch
->indexlist2
,
2265 #ifdef STANDALONE_SOLVER
2266 , "intersectional analysis,"
2267 " %d in block %s vs \\-diagonal",
2268 n
, usage
->blocks
->blocknames
[b
]
2271 diff
= max(diff
, DIFF_INTERSECT
);
2277 * Intersectional analysis, /-diagonal vs blocks.
2279 for (b
= 0; b
< cr
; b
++)
2280 for (n
= 1; n
<= cr
; n
++) {
2281 if (usage
->diag
[cr
+n
-1] ||
2282 usage
->blk
[b
*cr
+n
-1])
2284 for (i
= 0; i
< cr
; i
++) {
2285 scratch
->indexlist
[i
] = cubepos2(diag1(i
), n
);
2286 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
2288 if (solver_intersect(usage
, scratch
->indexlist
,
2290 #ifdef STANDALONE_SOLVER
2291 , "intersectional analysis,"
2292 " %d in /-diagonal vs block %s",
2293 n
, usage
->blocks
->blocknames
[b
]
2296 solver_intersect(usage
, scratch
->indexlist2
,
2298 #ifdef STANDALONE_SOLVER
2299 , "intersectional analysis,"
2300 " %d in block %s vs /-diagonal",
2301 n
, usage
->blocks
->blocknames
[b
]
2304 diff
= max(diff
, DIFF_INTERSECT
);
2310 if (dlev
->maxdiff
<= DIFF_INTERSECT
)
2314 * Blockwise set elimination.
2316 for (b
= 0; b
< cr
; b
++) {
2317 for (i
= 0; i
< cr
; i
++)
2318 for (n
= 1; n
<= cr
; n
++)
2319 scratch
->indexlist
[i
*cr
+n
-1] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
2320 ret
= solver_set(usage
, scratch
, scratch
->indexlist
2321 #ifdef STANDALONE_SOLVER
2322 , "set elimination, block %s",
2323 usage
->blocks
->blocknames
[b
]
2327 diff
= DIFF_IMPOSSIBLE
;
2329 } else if (ret
> 0) {
2330 diff
= max(diff
, DIFF_SET
);
2336 * Row-wise set elimination.
2338 for (y
= 0; y
< cr
; y
++) {
2339 for (x
= 0; x
< cr
; x
++)
2340 for (n
= 1; n
<= cr
; n
++)
2341 scratch
->indexlist
[x
*cr
+n
-1] = cubepos(x
, y
, n
);
2342 ret
= solver_set(usage
, scratch
, scratch
->indexlist
2343 #ifdef STANDALONE_SOLVER
2344 , "set elimination, row %d", 1+y
2348 diff
= DIFF_IMPOSSIBLE
;
2350 } else if (ret
> 0) {
2351 diff
= max(diff
, DIFF_SET
);
2357 * Column-wise set elimination.
2359 for (x
= 0; x
< cr
; x
++) {
2360 for (y
= 0; y
< cr
; y
++)
2361 for (n
= 1; n
<= cr
; n
++)
2362 scratch
->indexlist
[y
*cr
+n
-1] = cubepos(x
, y
, n
);
2363 ret
= solver_set(usage
, scratch
, scratch
->indexlist
2364 #ifdef STANDALONE_SOLVER
2365 , "set elimination, column %d", 1+x
2369 diff
= DIFF_IMPOSSIBLE
;
2371 } else if (ret
> 0) {
2372 diff
= max(diff
, DIFF_SET
);
2379 * \-diagonal set elimination.
2381 for (i
= 0; i
< cr
; i
++)
2382 for (n
= 1; n
<= cr
; n
++)
2383 scratch
->indexlist
[i
*cr
+n
-1] = cubepos2(diag0(i
), n
);
2384 ret
= solver_set(usage
, scratch
, scratch
->indexlist
2385 #ifdef STANDALONE_SOLVER
2386 , "set elimination, \\-diagonal"
2390 diff
= DIFF_IMPOSSIBLE
;
2392 } else if (ret
> 0) {
2393 diff
= max(diff
, DIFF_SET
);
2398 * /-diagonal set elimination.
2400 for (i
= 0; i
< cr
; i
++)
2401 for (n
= 1; n
<= cr
; n
++)
2402 scratch
->indexlist
[i
*cr
+n
-1] = cubepos2(diag1(i
), n
);
2403 ret
= solver_set(usage
, scratch
, scratch
->indexlist
2404 #ifdef STANDALONE_SOLVER
2405 , "set elimination, /-diagonal"
2409 diff
= DIFF_IMPOSSIBLE
;
2411 } else if (ret
> 0) {
2412 diff
= max(diff
, DIFF_SET
);
2417 if (dlev
->maxdiff
<= DIFF_SET
)
2421 * Row-vs-column set elimination on a single number.
2423 for (n
= 1; n
<= cr
; n
++) {
2424 for (y
= 0; y
< cr
; y
++)
2425 for (x
= 0; x
< cr
; x
++)
2426 scratch
->indexlist
[y
*cr
+x
] = cubepos(x
, y
, n
);
2427 ret
= solver_set(usage
, scratch
, scratch
->indexlist
2428 #ifdef STANDALONE_SOLVER
2429 , "positional set elimination, number %d", n
2433 diff
= DIFF_IMPOSSIBLE
;
2435 } else if (ret
> 0) {
2436 diff
= max(diff
, DIFF_EXTREME
);
2444 if (solver_forcing(usage
, scratch
)) {
2445 diff
= max(diff
, DIFF_EXTREME
);
2450 * If we reach here, we have made no deductions in this
2451 * iteration, so the algorithm terminates.
2457 * Last chance: if we haven't fully solved the puzzle yet, try
2458 * recursing based on guesses for a particular square. We pick
2459 * one of the most constrained empty squares we can find, which
2460 * has the effect of pruning the search tree as much as
2463 if (dlev
->maxdiff
>= DIFF_RECURSIVE
) {
2464 int best
, bestcount
;
2469 for (y
= 0; y
< cr
; y
++)
2470 for (x
= 0; x
< cr
; x
++)
2471 if (!grid
[y
*cr
+x
]) {
2475 * An unfilled square. Count the number of
2476 * possible digits in it.
2479 for (n
= 1; n
<= cr
; n
++)
2484 * We should have found any impossibilities
2485 * already, so this can safely be an assert.
2489 if (count
< bestcount
) {
2497 digit
*list
, *ingrid
, *outgrid
;
2499 diff
= DIFF_IMPOSSIBLE
; /* no solution found yet */
2502 * Attempt recursion.
2507 list
= snewn(cr
, digit
);
2508 ingrid
= snewn(cr
* cr
, digit
);
2509 outgrid
= snewn(cr
* cr
, digit
);
2510 memcpy(ingrid
, grid
, cr
* cr
);
2512 /* Make a list of the possible digits. */
2513 for (j
= 0, n
= 1; n
<= cr
; n
++)
2517 #ifdef STANDALONE_SOLVER
2518 if (solver_show_working
) {
2520 printf("%*srecursing on (%d,%d) [",
2521 solver_recurse_depth
*4, "", x
+ 1, y
+ 1);
2522 for (i
= 0; i
< j
; i
++) {
2523 printf("%s%d", sep
, list
[i
]);
2531 * And step along the list, recursing back into the
2532 * main solver at every stage.
2534 for (i
= 0; i
< j
; i
++) {
2535 memcpy(outgrid
, ingrid
, cr
* cr
);
2536 outgrid
[y
*cr
+x
] = list
[i
];
2538 #ifdef STANDALONE_SOLVER
2539 if (solver_show_working
)
2540 printf("%*sguessing %d at (%d,%d)\n",
2541 solver_recurse_depth
*4, "", list
[i
], x
+ 1, y
+ 1);
2542 solver_recurse_depth
++;
2545 solver(cr
, blocks
, kblocks
, xtype
, outgrid
, kgrid
, dlev
);
2547 #ifdef STANDALONE_SOLVER
2548 solver_recurse_depth
--;
2549 if (solver_show_working
) {
2550 printf("%*sretracting %d at (%d,%d)\n",
2551 solver_recurse_depth
*4, "", list
[i
], x
+ 1, y
+ 1);
2556 * If we have our first solution, copy it into the
2557 * grid we will return.
2559 if (diff
== DIFF_IMPOSSIBLE
&& dlev
->diff
!= DIFF_IMPOSSIBLE
)
2560 memcpy(grid
, outgrid
, cr
*cr
);
2562 if (dlev
->diff
== DIFF_AMBIGUOUS
)
2563 diff
= DIFF_AMBIGUOUS
;
2564 else if (dlev
->diff
== DIFF_IMPOSSIBLE
)
2565 /* do not change our return value */;
2567 /* the recursion turned up exactly one solution */
2568 if (diff
== DIFF_IMPOSSIBLE
)
2569 diff
= DIFF_RECURSIVE
;
2571 diff
= DIFF_AMBIGUOUS
;
2575 * As soon as we've found more than one solution,
2576 * give up immediately.
2578 if (diff
== DIFF_AMBIGUOUS
)
2589 * We're forbidden to use recursion, so we just see whether
2590 * our grid is fully solved, and return DIFF_IMPOSSIBLE
2593 for (y
= 0; y
< cr
; y
++)
2594 for (x
= 0; x
< cr
; x
++)
2596 diff
= DIFF_IMPOSSIBLE
;
2601 dlev
->kdiff
= kdiff
;
2603 #ifdef STANDALONE_SOLVER
2604 if (solver_show_working
)
2605 printf("%*s%s found\n",
2606 solver_recurse_depth
*4, "",
2607 diff
== DIFF_IMPOSSIBLE
? "no solution" :
2608 diff
== DIFF_AMBIGUOUS
? "multiple solutions" :
2612 sfree(usage
->sq2region
);
2613 sfree(usage
->regions
);
2618 if (usage
->kblocks
) {
2619 free_block_structure(usage
->kblocks
);
2620 free_block_structure(usage
->extra_cages
);
2621 sfree(usage
->extra_clues
);
2623 if (usage
->kclues
) sfree(usage
->kclues
);
2626 solver_free_scratch(scratch
);
2629 /* ----------------------------------------------------------------------
2630 * End of solver code.
2633 /* ----------------------------------------------------------------------
2634 * Killer set generator.
2637 /* ----------------------------------------------------------------------
2638 * Solo filled-grid generator.
2640 * This grid generator works by essentially trying to solve a grid
2641 * starting from no clues, and not worrying that there's more than
2642 * one possible solution. Unfortunately, it isn't computationally
2643 * feasible to do this by calling the above solver with an empty
2644 * grid, because that one needs to allocate a lot of scratch space
2645 * at every recursion level. Instead, I have a much simpler
2646 * algorithm which I shamelessly copied from a Python solver
2647 * written by Andrew Wilkinson (which is GPLed, but I've reused
2648 * only ideas and no code). It mostly just does the obvious
2649 * recursive thing: pick an empty square, put one of the possible
2650 * digits in it, recurse until all squares are filled, backtrack
2651 * and change some choices if necessary.
2653 * The clever bit is that every time it chooses which square to
2654 * fill in next, it does so by counting the number of _possible_
2655 * numbers that can go in each square, and it prioritises so that
2656 * it picks a square with the _lowest_ number of possibilities. The
2657 * idea is that filling in lots of the obvious bits (particularly
2658 * any squares with only one possibility) will cut down on the list
2659 * of possibilities for other squares and hence reduce the enormous
2660 * search space as much as possible as early as possible.
2662 * The use of bit sets implies that we support puzzles up to a size of
2663 * 32x32 (less if anyone finds a 16-bit machine to compile this on).
2667 * Internal data structure used in gridgen to keep track of
2670 struct gridgen_coord
{ int x
, y
, r
; };
2671 struct gridgen_usage
{
2673 struct block_structure
*blocks
, *kblocks
;
2674 /* grid is a copy of the input grid, modified as we go along */
2677 * Bitsets. In each of them, bit n is set if digit n has been placed
2678 * in the corresponding region. row, col and blk are used for all
2679 * puzzles. cge is used only for killer puzzles, and diag is used
2680 * only for x-type puzzles.
2681 * All of these have cr entries, except diag which only has 2,
2682 * and cge, which has as many entries as kblocks.
2684 unsigned int *row
, *col
, *blk
, *cge
, *diag
;
2685 /* This lists all the empty spaces remaining in the grid. */
2686 struct gridgen_coord
*spaces
;
2688 /* If we need randomisation in the solve, this is our random state. */
2692 static void gridgen_place(struct gridgen_usage
*usage
, int x
, int y
, digit n
)
2694 unsigned int bit
= 1 << n
;
2696 usage
->row
[y
] |= bit
;
2697 usage
->col
[x
] |= bit
;
2698 usage
->blk
[usage
->blocks
->whichblock
[y
*cr
+x
]] |= bit
;
2700 usage
->cge
[usage
->kblocks
->whichblock
[y
*cr
+x
]] |= bit
;
2702 if (ondiag0(y
*cr
+x
))
2703 usage
->diag
[0] |= bit
;
2704 if (ondiag1(y
*cr
+x
))
2705 usage
->diag
[1] |= bit
;
2707 usage
->grid
[y
*cr
+x
] = n
;
2710 static void gridgen_remove(struct gridgen_usage
*usage
, int x
, int y
, digit n
)
2712 unsigned int mask
= ~(1 << n
);
2714 usage
->row
[y
] &= mask
;
2715 usage
->col
[x
] &= mask
;
2716 usage
->blk
[usage
->blocks
->whichblock
[y
*cr
+x
]] &= mask
;
2718 usage
->cge
[usage
->kblocks
->whichblock
[y
*cr
+x
]] &= mask
;
2720 if (ondiag0(y
*cr
+x
))
2721 usage
->diag
[0] &= mask
;
2722 if (ondiag1(y
*cr
+x
))
2723 usage
->diag
[1] &= mask
;
2725 usage
->grid
[y
*cr
+x
] = 0;
2731 * The real recursive step in the generating function.
2733 * Return values: 1 means solution found, 0 means no solution
2734 * found on this branch.
2736 static int gridgen_real(struct gridgen_usage
*usage
, digit
*grid
, int *steps
)
2739 int i
, j
, n
, sx
, sy
, bestm
, bestr
, ret
;
2744 * Firstly, check for completion! If there are no spaces left
2745 * in the grid, we have a solution.
2747 if (usage
->nspaces
== 0)
2751 * Next, abandon generation if we went over our steps limit.
2758 * Otherwise, there must be at least one space. Find the most
2759 * constrained space, using the `r' field as a tie-breaker.
2761 bestm
= cr
+1; /* so that any space will beat it */
2765 for (j
= 0; j
< usage
->nspaces
; j
++) {
2766 int x
= usage
->spaces
[j
].x
, y
= usage
->spaces
[j
].y
;
2767 unsigned int used_xy
;
2770 m
= usage
->blocks
->whichblock
[y
*cr
+x
];
2771 used_xy
= usage
->row
[y
] | usage
->col
[x
] | usage
->blk
[m
];
2772 if (usage
->cge
!= NULL
)
2773 used_xy
|= usage
->cge
[usage
->kblocks
->whichblock
[y
*cr
+x
]];
2774 if (usage
->cge
!= NULL
)
2775 used_xy
|= usage
->cge
[usage
->kblocks
->whichblock
[y
*cr
+x
]];
2776 if (usage
->diag
!= NULL
) {
2777 if (ondiag0(y
*cr
+x
))
2778 used_xy
|= usage
->diag
[0];
2779 if (ondiag1(y
*cr
+x
))
2780 used_xy
|= usage
->diag
[1];
2784 * Find the number of digits that could go in this space.
2787 for (n
= 1; n
<= cr
; n
++) {
2788 unsigned int bit
= 1 << n
;
2789 if ((used_xy
& bit
) == 0)
2792 if (m
< bestm
|| (m
== bestm
&& usage
->spaces
[j
].r
< bestr
)) {
2794 bestr
= usage
->spaces
[j
].r
;
2803 * Swap that square into the final place in the spaces array,
2804 * so that decrementing nspaces will remove it from the list.
2806 if (i
!= usage
->nspaces
-1) {
2807 struct gridgen_coord t
;
2808 t
= usage
->spaces
[usage
->nspaces
-1];
2809 usage
->spaces
[usage
->nspaces
-1] = usage
->spaces
[i
];
2810 usage
->spaces
[i
] = t
;
2814 * Now we've decided which square to start our recursion at,
2815 * simply go through all possible values, shuffling them
2816 * randomly first if necessary.
2818 digits
= snewn(bestm
, int);
2821 for (n
= 1; n
<= cr
; n
++) {
2822 unsigned int bit
= 1 << n
;
2824 if ((used
& bit
) == 0)
2829 shuffle(digits
, j
, sizeof(*digits
), usage
->rs
);
2831 /* And finally, go through the digit list and actually recurse. */
2833 for (i
= 0; i
< j
; i
++) {
2836 /* Update the usage structure to reflect the placing of this digit. */
2837 gridgen_place(usage
, sx
, sy
, n
);
2840 /* Call the solver recursively. Stop when we find a solution. */
2841 if (gridgen_real(usage
, grid
, steps
)) {
2846 /* Revert the usage structure. */
2847 gridgen_remove(usage
, sx
, sy
, n
);
2856 * Entry point to generator. You give it parameters and a starting
2857 * grid, which is simply an array of cr*cr digits.
2859 static int gridgen(int cr
, struct block_structure
*blocks
,
2860 struct block_structure
*kblocks
, int xtype
,
2861 digit
*grid
, random_state
*rs
, int maxsteps
)
2863 struct gridgen_usage
*usage
;
2867 * Clear the grid to start with.
2869 memset(grid
, 0, cr
*cr
);
2872 * Create a gridgen_usage structure.
2874 usage
= snew(struct gridgen_usage
);
2877 usage
->blocks
= blocks
;
2881 usage
->row
= snewn(cr
, unsigned int);
2882 usage
->col
= snewn(cr
, unsigned int);
2883 usage
->blk
= snewn(cr
, unsigned int);
2884 if (kblocks
!= NULL
) {
2885 usage
->kblocks
= kblocks
;
2886 usage
->cge
= snewn(usage
->kblocks
->nr_blocks
, unsigned int);
2887 memset(usage
->cge
, FALSE
, kblocks
->nr_blocks
* sizeof *usage
->cge
);
2892 memset(usage
->row
, 0, cr
* sizeof *usage
->row
);
2893 memset(usage
->col
, 0, cr
* sizeof *usage
->col
);
2894 memset(usage
->blk
, 0, cr
* sizeof *usage
->blk
);
2897 usage
->diag
= snewn(2, unsigned int);
2898 memset(usage
->diag
, 0, 2 * sizeof *usage
->diag
);
2904 * Begin by filling in the whole top row with randomly chosen
2905 * numbers. This cannot introduce any bias or restriction on
2906 * the available grids, since we already know those numbers
2907 * are all distinct so all we're doing is choosing their
2910 for (x
= 0; x
< cr
; x
++)
2912 shuffle(grid
, cr
, sizeof(*grid
), rs
);
2913 for (x
= 0; x
< cr
; x
++)
2914 gridgen_place(usage
, x
, 0, grid
[x
]);
2916 usage
->spaces
= snewn(cr
* cr
, struct gridgen_coord
);
2922 * Initialise the list of grid spaces, taking care to leave
2923 * out the row I've already filled in above.
2925 for (y
= 1; y
< cr
; y
++) {
2926 for (x
= 0; x
< cr
; x
++) {
2927 usage
->spaces
[usage
->nspaces
].x
= x
;
2928 usage
->spaces
[usage
->nspaces
].y
= y
;
2929 usage
->spaces
[usage
->nspaces
].r
= random_bits(rs
, 31);
2935 * Run the real generator function.
2937 ret
= gridgen_real(usage
, grid
, &maxsteps
);
2940 * Clean up the usage structure now we have our answer.
2942 sfree(usage
->spaces
);
2952 /* ----------------------------------------------------------------------
2953 * End of grid generator code.
2957 * Check whether a grid contains a valid complete puzzle.
2959 static int check_valid(int cr
, struct block_structure
*blocks
,
2960 struct block_structure
*kblocks
, int xtype
, digit
*grid
)
2962 unsigned char *used
;
2965 used
= snewn(cr
, unsigned char);
2968 * Check that each row contains precisely one of everything.
2970 for (y
= 0; y
< cr
; y
++) {
2971 memset(used
, FALSE
, cr
);
2972 for (x
= 0; x
< cr
; x
++)
2973 if (grid
[y
*cr
+x
] > 0 && grid
[y
*cr
+x
] <= cr
)
2974 used
[grid
[y
*cr
+x
]-1] = TRUE
;
2975 for (n
= 0; n
< cr
; n
++)
2983 * Check that each column contains precisely one of everything.
2985 for (x
= 0; x
< cr
; x
++) {
2986 memset(used
, FALSE
, cr
);
2987 for (y
= 0; y
< cr
; y
++)
2988 if (grid
[y
*cr
+x
] > 0 && grid
[y
*cr
+x
] <= cr
)
2989 used
[grid
[y
*cr
+x
]-1] = TRUE
;
2990 for (n
= 0; n
< cr
; n
++)
2998 * Check that each block contains precisely one of everything.
3000 for (i
= 0; i
< cr
; i
++) {
3001 memset(used
, FALSE
, cr
);
3002 for (j
= 0; j
< cr
; j
++)
3003 if (grid
[blocks
->blocks
[i
][j
]] > 0 &&
3004 grid
[blocks
->blocks
[i
][j
]] <= cr
)
3005 used
[grid
[blocks
->blocks
[i
][j
]]-1] = TRUE
;
3006 for (n
= 0; n
< cr
; n
++)
3014 * Check that each Killer cage, if any, contains at most one of
3018 for (i
= 0; i
< kblocks
->nr_blocks
; i
++) {
3019 memset(used
, FALSE
, cr
);
3020 for (j
= 0; j
< kblocks
->nr_squares
[i
]; j
++)
3021 if (grid
[kblocks
->blocks
[i
][j
]] > 0 &&
3022 grid
[kblocks
->blocks
[i
][j
]] <= cr
) {
3023 if (used
[grid
[kblocks
->blocks
[i
][j
]]-1]) {
3027 used
[grid
[kblocks
->blocks
[i
][j
]]-1] = TRUE
;
3033 * Check that each diagonal contains precisely one of everything.
3036 memset(used
, FALSE
, cr
);
3037 for (i
= 0; i
< cr
; i
++)
3038 if (grid
[diag0(i
)] > 0 && grid
[diag0(i
)] <= cr
)
3039 used
[grid
[diag0(i
)]-1] = TRUE
;
3040 for (n
= 0; n
< cr
; n
++)
3045 for (i
= 0; i
< cr
; i
++)
3046 if (grid
[diag1(i
)] > 0 && grid
[diag1(i
)] <= cr
)
3047 used
[grid
[diag1(i
)]-1] = TRUE
;
3048 for (n
= 0; n
< cr
; n
++)
3059 static int symmetries(game_params
*params
, int x
, int y
, int *output
, int s
)
3061 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
3064 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
3070 break; /* just x,y is all we need */
3072 ADD(cr
- 1 - x
, cr
- 1 - y
);
3077 ADD(cr
- 1 - x
, cr
- 1 - y
);
3088 ADD(cr
- 1 - x
, cr
- 1 - y
);
3092 ADD(cr
- 1 - x
, cr
- 1 - y
);
3093 ADD(cr
- 1 - y
, cr
- 1 - x
);
3098 ADD(cr
- 1 - x
, cr
- 1 - y
);
3102 ADD(cr
- 1 - y
, cr
- 1 - x
);
3111 static char *encode_solve_move(int cr
, digit
*grid
)
3114 char *ret
, *p
, *sep
;
3117 * It's surprisingly easy to work out _exactly_ how long this
3118 * string needs to be. To decimal-encode all the numbers from 1
3121 * - every number has a units digit; total is n.
3122 * - all numbers above 9 have a tens digit; total is max(n-9,0).
3123 * - all numbers above 99 have a hundreds digit; total is max(n-99,0).
3127 for (i
= 1; i
<= cr
; i
*= 10)
3128 len
+= max(cr
- i
+ 1, 0);
3129 len
+= cr
; /* don't forget the commas */
3130 len
*= cr
; /* there are cr rows of these */
3133 * Now len is one bigger than the total size of the
3134 * comma-separated numbers (because we counted an
3135 * additional leading comma). We need to have a leading S
3136 * and a trailing NUL, so we're off by one in total.
3140 ret
= snewn(len
, char);
3144 for (i
= 0; i
< cr
*cr
; i
++) {
3145 p
+= sprintf(p
, "%s%d", sep
, grid
[i
]);
3149 assert(p
- ret
== len
);
3154 static void dsf_to_blocks(int *dsf
, struct block_structure
*blocks
,
3155 int min_expected
, int max_expected
)
3157 int cr
= blocks
->c
* blocks
->r
, area
= cr
* cr
;
3160 for (i
= 0; i
< area
; i
++)
3161 blocks
->whichblock
[i
] = -1;
3162 for (i
= 0; i
< area
; i
++) {
3163 int j
= dsf_canonify(dsf
, i
);
3164 if (blocks
->whichblock
[j
] < 0)
3165 blocks
->whichblock
[j
] = nb
++;
3166 blocks
->whichblock
[i
] = blocks
->whichblock
[j
];
3168 assert(nb
>= min_expected
&& nb
<= max_expected
);
3169 blocks
->nr_blocks
= nb
;
3172 static void make_blocks_from_whichblock(struct block_structure
*blocks
)
3176 for (i
= 0; i
< blocks
->nr_blocks
; i
++) {
3177 blocks
->blocks
[i
][blocks
->max_nr_squares
-1] = 0;
3178 blocks
->nr_squares
[i
] = 0;
3180 for (i
= 0; i
< blocks
->area
; i
++) {
3181 int b
= blocks
->whichblock
[i
];
3182 int j
= blocks
->blocks
[b
][blocks
->max_nr_squares
-1]++;
3183 assert(j
< blocks
->max_nr_squares
);
3184 blocks
->blocks
[b
][j
] = i
;
3185 blocks
->nr_squares
[b
]++;
3189 static char *encode_block_structure_desc(char *p
, struct block_structure
*blocks
)
3192 int c
= blocks
->c
, r
= blocks
->r
, cr
= c
* r
;
3195 * Encode the block structure. We do this by encoding
3196 * the pattern of dividing lines: first we iterate
3197 * over the cr*(cr-1) internal vertical grid lines in
3198 * ordinary reading order, then over the cr*(cr-1)
3199 * internal horizontal ones in transposed reading
3202 * We encode the number of non-lines between the
3203 * lines; _ means zero (two adjacent divisions), a
3204 * means 1, ..., y means 25, and z means 25 non-lines
3205 * _and no following line_ (so that za means 26, zb 27
3208 for (i
= 0; i
<= 2*cr
*(cr
-1); i
++) {
3209 int x
, y
, p0
, p1
, edge
;
3211 if (i
== 2*cr
*(cr
-1)) {
3212 edge
= TRUE
; /* terminating virtual edge */
3214 if (i
< cr
*(cr
-1)) {
3225 edge
= (blocks
->whichblock
[p0
] != blocks
->whichblock
[p1
]);
3229 while (currrun
> 25)
3230 *p
++ = 'z', currrun
-= 25;
3232 *p
++ = 'a'-1 + currrun
;
3242 static char *encode_grid(char *desc
, digit
*grid
, int area
)
3248 for (i
= 0; i
<= area
; i
++) {
3249 int n
= (i
< area
? grid
[i
] : -1);
3256 int c
= 'a' - 1 + run
;
3260 run
-= c
- ('a' - 1);
3264 * If there's a number in the very top left or
3265 * bottom right, there's no point putting an
3266 * unnecessary _ before or after it.
3268 if (p
> desc
&& n
> 0)
3272 p
+= sprintf(p
, "%d", n
);
3280 * Conservatively stimate the number of characters required for
3281 * encoding a grid of a certain area.
3283 static int grid_encode_space (int area
)
3286 for (count
= 1, t
= area
; t
> 26; t
-= 26)
3288 return count
* area
;
3292 * Conservatively stimate the number of characters required for
3293 * encoding a given blocks structure.
3295 static int blocks_encode_space(struct block_structure
*blocks
)
3297 int cr
= blocks
->c
* blocks
->r
, area
= cr
* cr
;
3298 return grid_encode_space(area
);
3301 static char *encode_puzzle_desc(game_params
*params
, digit
*grid
,
3302 struct block_structure
*blocks
,
3304 struct block_structure
*kblocks
)
3306 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
3311 space
= grid_encode_space(area
) + 1;
3313 space
+= blocks_encode_space(blocks
) + 1;
3314 if (params
->killer
) {
3315 space
+= blocks_encode_space(kblocks
) + 1;
3316 space
+= grid_encode_space(area
) + 1;
3318 desc
= snewn(space
, char);
3319 p
= encode_grid(desc
, grid
, area
);
3323 p
= encode_block_structure_desc(p
, blocks
);
3325 if (params
->killer
) {
3327 p
= encode_block_structure_desc(p
, kblocks
);
3329 p
= encode_grid(p
, kgrid
, area
);
3331 assert(p
- desc
< space
);
3333 desc
= sresize(desc
, p
- desc
, char);
3338 static void merge_blocks(struct block_structure
*b
, int n1
, int n2
)
3341 /* Move data towards the lower block number. */
3348 /* Merge n2 into n1, and move the last block into n2's position. */
3349 for (i
= 0; i
< b
->nr_squares
[n2
]; i
++)
3350 b
->whichblock
[b
->blocks
[n2
][i
]] = n1
;
3351 memcpy(b
->blocks
[n1
] + b
->nr_squares
[n1
], b
->blocks
[n2
],
3352 b
->nr_squares
[n2
] * sizeof **b
->blocks
);
3353 b
->nr_squares
[n1
] += b
->nr_squares
[n2
];
3355 n1
= b
->nr_blocks
- 1;
3357 memcpy(b
->blocks
[n2
], b
->blocks
[n1
],
3358 b
->nr_squares
[n1
] * sizeof **b
->blocks
);
3359 for (i
= 0; i
< b
->nr_squares
[n1
]; i
++)
3360 b
->whichblock
[b
->blocks
[n1
][i
]] = n2
;
3361 b
->nr_squares
[n2
] = b
->nr_squares
[n1
];
3366 static int merge_some_cages(struct block_structure
*b
, int cr
, int area
,
3367 digit
*grid
, random_state
*rs
)
3370 * Make a list of all the pairs of adjacent blocks.
3378 pairs
= snewn(b
->nr_blocks
* b
->nr_blocks
, struct pair
);
3381 for (i
= 0; i
< b
->nr_blocks
; i
++) {
3382 for (j
= i
+1; j
< b
->nr_blocks
; j
++) {
3385 * Rule the merger out of consideration if it's
3386 * obviously not viable.
3388 if (b
->nr_squares
[i
] + b
->nr_squares
[j
] > b
->max_nr_squares
)
3389 continue; /* we couldn't merge these anyway */
3392 * See if these two blocks have a pair of squares
3393 * adjacent to each other.
3395 for (k
= 0; k
< b
->nr_squares
[i
]; k
++) {
3396 int xy
= b
->blocks
[i
][k
];
3397 int y
= xy
/ cr
, x
= xy
% cr
;
3398 if ((y
> 0 && b
->whichblock
[xy
- cr
] == j
) ||
3399 (y
+1 < cr
&& b
->whichblock
[xy
+ cr
] == j
) ||
3400 (x
> 0 && b
->whichblock
[xy
- 1] == j
) ||
3401 (x
+1 < cr
&& b
->whichblock
[xy
+ 1] == j
)) {
3403 * Yes! Add this pair to our list.
3405 pairs
[npairs
].b1
= i
;
3406 pairs
[npairs
].b2
= j
;
3414 * Now go through that list in random order until we find a pair
3415 * of blocks we can merge.
3417 while (npairs
> 0) {
3419 unsigned int digits_found
;
3422 * Pick a random pair, and remove it from the list.
3424 i
= random_upto(rs
, npairs
);
3428 pairs
[i
] = pairs
[npairs
-1];
3431 /* Guarantee that the merged cage would still be a region. */
3433 for (i
= 0; i
< b
->nr_squares
[n1
]; i
++)
3434 digits_found
|= 1 << grid
[b
->blocks
[n1
][i
]];
3435 for (i
= 0; i
< b
->nr_squares
[n2
]; i
++)
3436 if (digits_found
& (1 << grid
[b
->blocks
[n2
][i
]]))
3438 if (i
!= b
->nr_squares
[n2
])
3442 * Got one! Do the merge.
3444 merge_blocks(b
, n1
, n2
);
3453 static void compute_kclues(struct block_structure
*cages
, digit
*kclues
,
3454 digit
*grid
, int area
)
3457 memset(kclues
, 0, area
* sizeof *kclues
);
3458 for (i
= 0; i
< cages
->nr_blocks
; i
++) {
3460 for (j
= 0; j
< area
; j
++)
3461 if (cages
->whichblock
[j
] == i
)
3463 for (j
= 0; j
< area
; j
++)
3464 if (cages
->whichblock
[j
] == i
)
3471 static struct block_structure
*gen_killer_cages(int cr
, random_state
*rs
,
3472 int remove_singletons
)
3475 int x
, y
, area
= cr
* cr
;
3476 int n_singletons
= 0;
3477 struct block_structure
*b
= alloc_block_structure (1, cr
, area
, cr
, area
);
3479 for (x
= 0; x
< area
; x
++)
3480 b
->whichblock
[x
] = -1;
3482 for (y
= 0; y
< cr
; y
++)
3483 for (x
= 0; x
< cr
; x
++) {
3486 if (b
->whichblock
[xy
] != -1)
3488 b
->whichblock
[xy
] = nr
;
3490 rnd
= random_bits(rs
, 4);
3491 if (xy
+ 1 < area
&& (rnd
>= 4 || (!remove_singletons
&& rnd
>= 1))) {
3493 if (x
+ 1 == cr
|| b
->whichblock
[xy2
] != -1 ||
3494 (xy
+ cr
< area
&& random_bits(rs
, 1) == 0))
3499 b
->whichblock
[xy2
] = nr
;
3506 make_blocks_from_whichblock(b
);
3508 for (x
= y
= 0; x
< b
->nr_blocks
; x
++)
3509 if (b
->nr_squares
[x
] == 1)
3511 assert(y
== n_singletons
);
3513 if (n_singletons
> 0 && remove_singletons
) {
3515 for (n
= 0; n
< b
->nr_blocks
;) {
3516 int xy
, x
, y
, xy2
, other
;
3517 if (b
->nr_squares
[n
] > 1) {
3521 xy
= b
->blocks
[n
][0];
3526 else if (x
+ 1 < cr
&& (y
+ 1 == cr
|| random_bits(rs
, 1) == 0))
3530 other
= b
->whichblock
[xy2
];
3532 if (b
->nr_squares
[other
] == 1)
3535 merge_blocks(b
, n
, other
);
3539 assert(n_singletons
== 0);
3544 static char *new_game_desc(game_params
*params
, random_state
*rs
,
3545 char **aux
, int interactive
)
3547 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
3549 struct block_structure
*blocks
, *kblocks
;
3550 digit
*grid
, *grid2
, *kgrid
;
3551 struct xy
{ int x
, y
; } *locs
;
3554 int coords
[16], ncoords
;
3556 struct difficulty dlev
;
3558 precompute_sum_bits();
3561 * Adjust the maximum difficulty level to be consistent with
3562 * the puzzle size: all 2x2 puzzles appear to be Trivial
3563 * (DIFF_BLOCK) so we cannot hold out for even a Basic
3564 * (DIFF_SIMPLE) one.
3566 dlev
.maxdiff
= params
->diff
;
3567 dlev
.maxkdiff
= params
->kdiff
;
3568 if (c
== 2 && r
== 2)
3569 dlev
.maxdiff
= DIFF_BLOCK
;
3571 grid
= snewn(area
, digit
);
3572 locs
= snewn(area
, struct xy
);
3573 grid2
= snewn(area
, digit
);
3575 blocks
= alloc_block_structure (c
, r
, area
, cr
, cr
);
3578 kgrid
= (params
->killer
) ? snewn(area
, digit
) : NULL
;
3580 #ifdef STANDALONE_SOLVER
3581 assert(!"This should never happen, so we don't need to create blocknames");
3585 * Loop until we get a grid of the required difficulty. This is
3586 * nasty, but it seems to be unpleasantly hard to generate
3587 * difficult grids otherwise.
3591 * Generate a random solved state, starting by
3592 * constructing the block structure.
3594 if (r
== 1) { /* jigsaw mode */
3595 int *dsf
= divvy_rectangle(cr
, cr
, cr
, rs
);
3597 dsf_to_blocks (dsf
, blocks
, cr
, cr
);
3600 } else { /* basic Sudoku mode */
3601 for (y
= 0; y
< cr
; y
++)
3602 for (x
= 0; x
< cr
; x
++)
3603 blocks
->whichblock
[y
*cr
+x
] = (y
/c
) * c
+ (x
/r
);
3605 make_blocks_from_whichblock(blocks
);
3607 if (params
->killer
) {
3608 if (kblocks
) free_block_structure(kblocks
);
3609 kblocks
= gen_killer_cages(cr
, rs
, params
->kdiff
> DIFF_KSINGLE
);
3612 if (!gridgen(cr
, blocks
, kblocks
, params
->xtype
, grid
, rs
, area
*area
))
3614 assert(check_valid(cr
, blocks
, kblocks
, params
->xtype
, grid
));
3617 * Save the solved grid in aux.
3621 * We might already have written *aux the last time we
3622 * went round this loop, in which case we should free
3623 * the old aux before overwriting it with the new one.
3629 *aux
= encode_solve_move(cr
, grid
);
3633 * Now we have a solved grid. For normal puzzles, we start removing
3634 * things from it while preserving solubility. Killer puzzles are
3635 * different: we just pass the empty grid to the solver, and use
3636 * the puzzle if it comes back solved.
3639 if (params
->killer
) {
3640 struct block_structure
*good_cages
= NULL
;
3641 struct block_structure
*last_cages
= NULL
;
3644 memcpy(grid2
, grid
, area
);
3647 compute_kclues(kblocks
, kgrid
, grid2
, area
);
3649 memset(grid
, 0, area
* sizeof *grid
);
3650 solver(cr
, blocks
, kblocks
, params
->xtype
, grid
, kgrid
, &dlev
);
3651 if (dlev
.diff
== dlev
.maxdiff
&& dlev
.kdiff
== dlev
.maxkdiff
) {
3653 * We have one that matches our difficulty. Store it for
3654 * later, but keep going.
3657 free_block_structure(good_cages
);
3659 good_cages
= dup_block_structure(kblocks
);
3660 if (!merge_some_cages(kblocks
, cr
, area
, grid2
, rs
))
3662 } else if (dlev
.diff
> dlev
.maxdiff
|| dlev
.kdiff
> dlev
.maxkdiff
) {
3664 * Give up after too many tries and either use the good one we
3665 * found, or generate a new grid.
3670 * The difficulty level got too high. If we have a good
3671 * one, use it, otherwise go back to the last one that
3672 * was at a lower difficulty and restart the process from
3675 if (good_cages
!= NULL
) {
3676 free_block_structure(kblocks
);
3677 kblocks
= dup_block_structure(good_cages
);
3678 if (!merge_some_cages(kblocks
, cr
, area
, grid2
, rs
))
3681 if (last_cages
== NULL
)
3683 free_block_structure(kblocks
);
3684 kblocks
= last_cages
;
3689 free_block_structure(last_cages
);
3690 last_cages
= dup_block_structure(kblocks
);
3691 if (!merge_some_cages(kblocks
, cr
, area
, grid2
, rs
))
3696 free_block_structure(last_cages
);
3697 if (good_cages
!= NULL
) {
3698 free_block_structure(kblocks
);
3699 kblocks
= good_cages
;
3700 compute_kclues(kblocks
, kgrid
, grid2
, area
);
3701 memset(grid
, 0, area
* sizeof *grid
);
3708 * Find the set of equivalence classes of squares permitted
3709 * by the selected symmetry. We do this by enumerating all
3710 * the grid squares which have no symmetric companion
3711 * sorting lower than themselves.
3714 for (y
= 0; y
< cr
; y
++)
3715 for (x
= 0; x
< cr
; x
++) {
3719 ncoords
= symmetries(params
, x
, y
, coords
, params
->symm
);
3720 for (j
= 0; j
< ncoords
; j
++)
3721 if (coords
[2*j
+1]*cr
+coords
[2*j
] < i
)
3731 * Now shuffle that list.
3733 shuffle(locs
, nlocs
, sizeof(*locs
), rs
);
3736 * Now loop over the shuffled list and, for each element,
3737 * see whether removing that element (and its reflections)
3738 * from the grid will still leave the grid soluble.
3740 for (i
= 0; i
< nlocs
; i
++) {
3744 memcpy(grid2
, grid
, area
);
3745 ncoords
= symmetries(params
, x
, y
, coords
, params
->symm
);
3746 for (j
= 0; j
< ncoords
; j
++)
3747 grid2
[coords
[2*j
+1]*cr
+coords
[2*j
]] = 0;
3749 solver(cr
, blocks
, kblocks
, params
->xtype
, grid2
, kgrid
, &dlev
);
3750 if (dlev
.diff
<= dlev
.maxdiff
&&
3751 (!params
->killer
|| dlev
.kdiff
<= dlev
.maxkdiff
)) {
3752 for (j
= 0; j
< ncoords
; j
++)
3753 grid
[coords
[2*j
+1]*cr
+coords
[2*j
]] = 0;
3757 memcpy(grid2
, grid
, area
);
3759 solver(cr
, blocks
, kblocks
, params
->xtype
, grid2
, kgrid
, &dlev
);
3760 if (dlev
.diff
== dlev
.maxdiff
&&
3761 (!params
->killer
|| dlev
.kdiff
== dlev
.maxkdiff
))
3762 break; /* found one! */
3769 * Now we have the grid as it will be presented to the user.
3770 * Encode it in a game desc.
3772 desc
= encode_puzzle_desc(params
, grid
, blocks
, kgrid
, kblocks
);
3775 free_block_structure(blocks
);
3776 if (params
->killer
) {
3777 free_block_structure(kblocks
);
3784 static char *spec_to_grid(char *desc
, digit
*grid
, int area
)
3787 while (*desc
&& *desc
!= ',') {
3789 if (n
>= 'a' && n
<= 'z') {
3790 int run
= n
- 'a' + 1;
3791 assert(i
+ run
<= area
);
3794 } else if (n
== '_') {
3796 } else if (n
> '0' && n
<= '9') {
3798 grid
[i
++] = atoi(desc
-1);
3799 while (*desc
>= '0' && *desc
<= '9')
3802 assert(!"We can't get here");
3810 * Create a DSF from a spec found in *pdesc. Update this to point past the
3811 * end of the block spec, and return an error string or NULL if everything
3812 * is OK. The DSF is stored in *PDSF.
3814 static char *spec_to_dsf(char **pdesc
, int **pdsf
, int cr
, int area
)
3816 char *desc
= *pdesc
;
3820 *pdsf
= dsf
= snew_dsf(area
);
3822 while (*desc
&& *desc
!= ',') {
3827 else if (*desc
>= 'a' && *desc
<= 'z')
3828 c
= *desc
- 'a' + 1;
3831 return "Invalid character in game description";
3835 adv
= (c
!= 25); /* 'z' is a special case */
3841 * Non-edge; merge the two dsf classes on either
3844 assert(pos
< 2*cr
*(cr
-1));
3845 if (pos
< cr
*(cr
-1)) {
3851 int x
= pos
/(cr
-1) - cr
;
3856 dsf_merge(dsf
, p0
, p1
);
3866 * When desc is exhausted, we expect to have gone exactly
3867 * one space _past_ the end of the grid, due to the dummy
3870 if (pos
!= 2*cr
*(cr
-1)+1) {
3872 return "Not enough data in block structure specification";
3878 static char *validate_grid_desc(char **pdesc
, int range
, int area
)
3880 char *desc
= *pdesc
;
3882 while (*desc
&& *desc
!= ',') {
3884 if (n
>= 'a' && n
<= 'z') {
3885 squares
+= n
- 'a' + 1;
3886 } else if (n
== '_') {
3888 } else if (n
> '0' && n
<= '9') {
3889 int val
= atoi(desc
-1);
3890 if (val
< 1 || val
> range
)
3891 return "Out-of-range number in game description";
3893 while (*desc
>= '0' && *desc
<= '9')
3896 return "Invalid character in game description";
3900 return "Not enough data to fill grid";
3903 return "Too much data to fit in grid";
3908 static char *validate_block_desc(char **pdesc
, int cr
, int area
,
3909 int min_nr_blocks
, int max_nr_blocks
,
3910 int min_nr_squares
, int max_nr_squares
)
3915 err
= spec_to_dsf(pdesc
, &dsf
, cr
, area
);
3920 if (min_nr_squares
== max_nr_squares
) {
3921 assert(min_nr_blocks
== max_nr_blocks
);
3922 assert(min_nr_blocks
* min_nr_squares
== area
);
3925 * Now we've got our dsf. Verify that it matches
3929 int *canons
, *counts
;
3930 int i
, j
, c
, ncanons
= 0;
3932 canons
= snewn(max_nr_blocks
, int);
3933 counts
= snewn(max_nr_blocks
, int);
3935 for (i
= 0; i
< area
; i
++) {
3936 j
= dsf_canonify(dsf
, i
);
3938 for (c
= 0; c
< ncanons
; c
++)
3939 if (canons
[c
] == j
) {
3941 if (counts
[c
] > max_nr_squares
) {
3945 return "A jigsaw block is too big";
3951 if (ncanons
>= max_nr_blocks
) {
3955 return "Too many distinct jigsaw blocks";
3957 canons
[ncanons
] = j
;
3958 counts
[ncanons
] = 1;
3963 if (ncanons
< min_nr_blocks
) {
3967 return "Not enough distinct jigsaw blocks";
3969 for (c
= 0; c
< ncanons
; c
++) {
3970 if (counts
[c
] < min_nr_squares
) {
3974 return "A jigsaw block is too small";
3985 static char *validate_desc(game_params
*params
, char *desc
)
3987 int cr
= params
->c
* params
->r
, area
= cr
*cr
;
3990 err
= validate_grid_desc(&desc
, cr
, area
);
3994 if (params
->r
== 1) {
3996 * Now we expect a suffix giving the jigsaw block
3997 * structure. Parse it and validate that it divides the
3998 * grid into the right number of regions which are the
4002 return "Expected jigsaw block structure in game description";
4004 err
= validate_block_desc(&desc
, cr
, area
, cr
, cr
, cr
, cr
);
4009 if (params
->killer
) {
4011 return "Expected killer block structure in game description";
4013 err
= validate_block_desc(&desc
, cr
, area
, cr
, area
, 2, cr
);
4017 return "Expected killer clue grid in game description";
4019 err
= validate_grid_desc(&desc
, cr
* area
, area
);
4024 return "Unexpected data at end of game description";
4029 static game_state
*new_game(midend
*me
, game_params
*params
, char *desc
)
4031 game_state
*state
= snew(game_state
);
4032 int c
= params
->c
, r
= params
->r
, cr
= c
*r
, area
= cr
* cr
;
4035 precompute_sum_bits();
4038 state
->xtype
= params
->xtype
;
4039 state
->killer
= params
->killer
;
4041 state
->grid
= snewn(area
, digit
);
4042 state
->pencil
= snewn(area
* cr
, unsigned char);
4043 memset(state
->pencil
, 0, area
* cr
);
4044 state
->immutable
= snewn(area
, unsigned char);
4045 memset(state
->immutable
, FALSE
, area
);
4047 state
->blocks
= alloc_block_structure (c
, r
, area
, cr
, cr
);
4049 if (params
->killer
) {
4050 state
->kblocks
= alloc_block_structure (c
, r
, area
, cr
, area
);
4051 state
->kgrid
= snewn(area
, digit
);
4053 state
->kblocks
= NULL
;
4054 state
->kgrid
= NULL
;
4056 state
->completed
= state
->cheated
= FALSE
;
4058 desc
= spec_to_grid(desc
, state
->grid
, area
);
4059 for (i
= 0; i
< area
; i
++)
4060 if (state
->grid
[i
] != 0)
4061 state
->immutable
[i
] = TRUE
;
4066 assert(*desc
== ',');
4068 err
= spec_to_dsf(&desc
, &dsf
, cr
, area
);
4069 assert(err
== NULL
);
4070 dsf_to_blocks(dsf
, state
->blocks
, cr
, cr
);
4075 for (y
= 0; y
< cr
; y
++)
4076 for (x
= 0; x
< cr
; x
++)
4077 state
->blocks
->whichblock
[y
*cr
+x
] = (y
/c
) * c
+ (x
/r
);
4079 make_blocks_from_whichblock(state
->blocks
);
4081 if (params
->killer
) {
4084 assert(*desc
== ',');
4086 err
= spec_to_dsf(&desc
, &dsf
, cr
, area
);
4087 assert(err
== NULL
);
4088 dsf_to_blocks(dsf
, state
->kblocks
, cr
, area
);
4090 make_blocks_from_whichblock(state
->kblocks
);
4092 assert(*desc
== ',');
4094 desc
= spec_to_grid(desc
, state
->kgrid
, area
);
4098 #ifdef STANDALONE_SOLVER
4100 * Set up the block names for solver diagnostic output.
4103 char *p
= (char *)(state
->blocks
->blocknames
+ cr
);
4106 for (i
= 0; i
< area
; i
++) {
4107 int j
= state
->blocks
->whichblock
[i
];
4108 if (!state
->blocks
->blocknames
[j
]) {
4109 state
->blocks
->blocknames
[j
] = p
;
4110 p
+= 1 + sprintf(p
, "starting at (%d,%d)",
4111 1 + i
%cr
, 1 + i
/cr
);
4116 for (by
= 0; by
< r
; by
++)
4117 for (bx
= 0; bx
< c
; bx
++) {
4118 state
->blocks
->blocknames
[by
*c
+bx
] = p
;
4119 p
+= 1 + sprintf(p
, "(%d,%d)", bx
+1, by
+1);
4122 assert(p
- (char *)state
->blocks
->blocknames
< (int)(cr
*(sizeof(char *)+80)));
4123 for (i
= 0; i
< cr
; i
++)
4124 assert(state
->blocks
->blocknames
[i
]);
4131 static game_state
*dup_game(game_state
*state
)
4133 game_state
*ret
= snew(game_state
);
4134 int cr
= state
->cr
, area
= cr
* cr
;
4136 ret
->cr
= state
->cr
;
4137 ret
->xtype
= state
->xtype
;
4138 ret
->killer
= state
->killer
;
4140 ret
->blocks
= state
->blocks
;
4141 ret
->blocks
->refcount
++;
4143 ret
->kblocks
= state
->kblocks
;
4145 ret
->kblocks
->refcount
++;
4147 ret
->grid
= snewn(area
, digit
);
4148 memcpy(ret
->grid
, state
->grid
, area
);
4150 if (state
->killer
) {
4151 ret
->kgrid
= snewn(area
, digit
);
4152 memcpy(ret
->kgrid
, state
->kgrid
, area
);
4156 ret
->pencil
= snewn(area
* cr
, unsigned char);
4157 memcpy(ret
->pencil
, state
->pencil
, area
* cr
);
4159 ret
->immutable
= snewn(area
, unsigned char);
4160 memcpy(ret
->immutable
, state
->immutable
, area
);
4162 ret
->completed
= state
->completed
;
4163 ret
->cheated
= state
->cheated
;
4168 static void free_game(game_state
*state
)
4170 free_block_structure(state
->blocks
);
4172 free_block_structure(state
->kblocks
);
4174 sfree(state
->immutable
);
4175 sfree(state
->pencil
);
4177 if (state
->kgrid
) sfree(state
->kgrid
);
4181 static char *solve_game(game_state
*state
, game_state
*currstate
,
4182 char *ai
, char **error
)
4187 struct difficulty dlev
;
4190 * If we already have the solution in ai, save ourselves some
4196 grid
= snewn(cr
*cr
, digit
);
4197 memcpy(grid
, state
->grid
, cr
*cr
);
4198 dlev
.maxdiff
= DIFF_RECURSIVE
;
4199 dlev
.maxkdiff
= DIFF_KINTERSECT
;
4200 solver(cr
, state
->blocks
, state
->kblocks
, state
->xtype
, grid
,
4201 state
->kgrid
, &dlev
);
4205 if (dlev
.diff
== DIFF_IMPOSSIBLE
)
4206 *error
= "No solution exists for this puzzle";
4207 else if (dlev
.diff
== DIFF_AMBIGUOUS
)
4208 *error
= "Multiple solutions exist for this puzzle";
4215 ret
= encode_solve_move(cr
, grid
);
4222 static char *grid_text_format(int cr
, struct block_structure
*blocks
,
4223 int xtype
, digit
*grid
)
4227 int totallen
, linelen
, nlines
;
4231 * For non-jigsaw Sudoku, we format in the way we always have,
4232 * by having the digits unevenly spaced so that the dividing
4241 * For jigsaw puzzles, however, we must leave space between
4242 * _all_ pairs of digits for an optional dividing line, so we
4243 * have to move to the rather ugly
4253 * We deal with both cases using the same formatting code; we
4254 * simply invent a vmod value such that there's a vertical
4255 * dividing line before column i iff i is divisible by vmod
4256 * (so it's r in the first case and 1 in the second), and hmod
4257 * likewise for horizontal dividing lines.
4260 if (blocks
->r
!= 1) {
4268 * Line length: we have cr digits, each with a space after it,
4269 * and (cr-1)/vmod dividing lines, each with a space after it.
4270 * The final space is replaced by a newline, but that doesn't
4271 * affect the length.
4273 linelen
= 2*(cr
+ (cr
-1)/vmod
);
4276 * Number of lines: we have cr rows of digits, and (cr-1)/hmod
4279 nlines
= cr
+ (cr
-1)/hmod
;
4282 * Allocate the space.
4284 totallen
= linelen
* nlines
;
4285 ret
= snewn(totallen
+1, char); /* leave room for terminating NUL */
4291 for (y
= 0; y
< cr
; y
++) {
4295 for (x
= 0; x
< cr
; x
++) {
4299 digit d
= grid
[y
*cr
+x
];
4303 * Empty space: we usually write a dot, but we'll
4304 * highlight spaces on the X-diagonals (in X mode)
4305 * by using underscores instead.
4307 if (xtype
&& (ondiag0(y
*cr
+x
) || ondiag1(y
*cr
+x
)))
4311 } else if (d
<= 9) {
4328 * Optional dividing line.
4330 if (blocks
->whichblock
[y
*cr
+x
] != blocks
->whichblock
[y
*cr
+x
+1])
4337 if (y
== cr
-1 || (y
+1) % hmod
)
4343 for (x
= 0; x
< cr
; x
++) {
4348 * Division between two squares. This varies
4349 * complicatedly in length.
4351 dwid
= 2; /* digit and its following space */
4353 dwid
--; /* no following space at end of line */
4354 if (x
> 0 && x
% vmod
== 0)
4355 dwid
++; /* preceding space after a divider */
4357 if (blocks
->whichblock
[y
*cr
+x
] != blocks
->whichblock
[(y
+1)*cr
+x
])
4374 * Corner square. This is:
4375 * - a space if all four surrounding squares are in
4377 * - a vertical line if the two left ones are in one
4378 * block and the two right in another
4379 * - a horizontal line if the two top ones are in one
4380 * block and the two bottom in another
4381 * - a plus sign in all other cases. (If we had a
4382 * richer character set available we could break
4383 * this case up further by doing fun things with
4384 * line-drawing T-pieces.)
4386 tl
= blocks
->whichblock
[y
*cr
+x
];
4387 tr
= blocks
->whichblock
[y
*cr
+x
+1];
4388 bl
= blocks
->whichblock
[(y
+1)*cr
+x
];
4389 br
= blocks
->whichblock
[(y
+1)*cr
+x
+1];
4391 if (tl
== tr
&& tr
== bl
&& bl
== br
)
4393 else if (tl
== bl
&& tr
== br
)
4395 else if (tl
== tr
&& bl
== br
)
4404 assert(p
- ret
== totallen
);
4409 static int game_can_format_as_text_now(game_params
*params
)
4412 * Formatting Killer puzzles as text is currently unsupported. I
4413 * can't think of any sensible way of doing it which doesn't
4414 * involve expanding the puzzle to such a large scale as to make
4422 static char *game_text_format(game_state
*state
)
4424 assert(!state
->kblocks
);
4425 return grid_text_format(state
->cr
, state
->blocks
, state
->xtype
,
4431 * These are the coordinates of the currently highlighted
4432 * square on the grid, if hshow = 1.
4436 * This indicates whether the current highlight is a
4437 * pencil-mark one or a real one.
4441 * This indicates whether or not we're showing the highlight
4442 * (used to be hx = hy = -1); important so that when we're
4443 * using the cursor keys it doesn't keep coming back at a
4444 * fixed position. When hshow = 1, pressing a valid number
4445 * or letter key or Space will enter that number or letter in the grid.
4449 * This indicates whether we're using the highlight as a cursor;
4450 * it means that it doesn't vanish on a keypress, and that it is
4451 * allowed on immutable squares.
4456 static game_ui
*new_ui(game_state
*state
)
4458 game_ui
*ui
= snew(game_ui
);
4460 ui
->hx
= ui
->hy
= 0;
4461 ui
->hpencil
= ui
->hshow
= ui
->hcursor
= 0;
4466 static void free_ui(game_ui
*ui
)
4471 static char *encode_ui(game_ui
*ui
)
4476 static void decode_ui(game_ui
*ui
, char *encoding
)
4480 static void game_changed_state(game_ui
*ui
, game_state
*oldstate
,
4481 game_state
*newstate
)
4483 int cr
= newstate
->cr
;
4485 * We prevent pencil-mode highlighting of a filled square, unless
4486 * we're using the cursor keys. So if the user has just filled in
4487 * a square which we had a pencil-mode highlight in (by Undo, or
4488 * by Redo, or by Solve), then we cancel the highlight.
4490 if (ui
->hshow
&& ui
->hpencil
&& !ui
->hcursor
&&
4491 newstate
->grid
[ui
->hy
* cr
+ ui
->hx
] != 0) {
4496 struct game_drawstate
{
4501 unsigned char *pencil
;
4503 /* This is scratch space used within a single call to game_redraw. */
4504 int nregions
, *entered_items
;
4507 static char *interpret_move(game_state
*state
, game_ui
*ui
, game_drawstate
*ds
,
4508 int x
, int y
, int button
)
4514 button
&= ~MOD_MASK
;
4516 tx
= (x
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
4517 ty
= (y
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
4519 if (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
) {
4520 if (button
== LEFT_BUTTON
) {
4521 if (state
->immutable
[ty
*cr
+tx
]) {
4523 } else if (tx
== ui
->hx
&& ty
== ui
->hy
&&
4524 ui
->hshow
&& ui
->hpencil
== 0) {
4533 return ""; /* UI activity occurred */
4535 if (button
== RIGHT_BUTTON
) {
4537 * Pencil-mode highlighting for non filled squares.
4539 if (state
->grid
[ty
*cr
+tx
] == 0) {
4540 if (tx
== ui
->hx
&& ty
== ui
->hy
&&
4541 ui
->hshow
&& ui
->hpencil
) {
4553 return ""; /* UI activity occurred */
4556 if (IS_CURSOR_MOVE(button
)) {
4557 move_cursor(button
, &ui
->hx
, &ui
->hy
, cr
, cr
, 0);
4558 ui
->hshow
= ui
->hcursor
= 1;
4562 (button
== CURSOR_SELECT
)) {
4563 ui
->hpencil
= 1 - ui
->hpencil
;
4569 ((button
>= '0' && button
<= '9' && button
- '0' <= cr
) ||
4570 (button
>= 'a' && button
<= 'z' && button
- 'a' + 10 <= cr
) ||
4571 (button
>= 'A' && button
<= 'Z' && button
- 'A' + 10 <= cr
) ||
4572 button
== CURSOR_SELECT2
|| button
== '\b')) {
4573 int n
= button
- '0';
4574 if (button
>= 'A' && button
<= 'Z')
4575 n
= button
- 'A' + 10;
4576 if (button
>= 'a' && button
<= 'z')
4577 n
= button
- 'a' + 10;
4578 if (button
== CURSOR_SELECT2
|| button
== '\b')
4582 * Can't overwrite this square. This can only happen here
4583 * if we're using the cursor keys.
4585 if (state
->immutable
[ui
->hy
*cr
+ui
->hx
])
4589 * Can't make pencil marks in a filled square. Again, this
4590 * can only become highlighted if we're using cursor keys.
4592 if (ui
->hpencil
&& state
->grid
[ui
->hy
*cr
+ui
->hx
])
4595 sprintf(buf
, "%c%d,%d,%d",
4596 (char)(ui
->hpencil
&& n
> 0 ? 'P' : 'R'), ui
->hx
, ui
->hy
, n
);
4598 if (!ui
->hcursor
) ui
->hshow
= 0;
4606 static game_state
*execute_move(game_state
*from
, char *move
)
4612 if (move
[0] == 'S') {
4615 ret
= dup_game(from
);
4616 ret
->completed
= ret
->cheated
= TRUE
;
4619 for (n
= 0; n
< cr
*cr
; n
++) {
4620 ret
->grid
[n
] = atoi(p
);
4622 if (!*p
|| ret
->grid
[n
] < 1 || ret
->grid
[n
] > cr
) {
4627 while (*p
&& isdigit((unsigned char)*p
)) p
++;
4632 } else if ((move
[0] == 'P' || move
[0] == 'R') &&
4633 sscanf(move
+1, "%d,%d,%d", &x
, &y
, &n
) == 3 &&
4634 x
>= 0 && x
< cr
&& y
>= 0 && y
< cr
&& n
>= 0 && n
<= cr
) {
4636 ret
= dup_game(from
);
4637 if (move
[0] == 'P' && n
> 0) {
4638 int index
= (y
*cr
+x
) * cr
+ (n
-1);
4639 ret
->pencil
[index
] = !ret
->pencil
[index
];
4641 ret
->grid
[y
*cr
+x
] = n
;
4642 memset(ret
->pencil
+ (y
*cr
+x
)*cr
, 0, cr
);
4645 * We've made a real change to the grid. Check to see
4646 * if the game has been completed.
4648 if (!ret
->completed
&& check_valid(cr
, ret
->blocks
, ret
->kblocks
,
4649 ret
->xtype
, ret
->grid
)) {
4650 ret
->completed
= TRUE
;
4655 return NULL
; /* couldn't parse move string */
4658 /* ----------------------------------------------------------------------
4662 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
4663 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
4665 static void game_compute_size(game_params
*params
, int tilesize
,
4668 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
4669 struct { int tilesize
; } ads
, *ds
= &ads
;
4670 ads
.tilesize
= tilesize
;
4672 *x
= SIZE(params
->c
* params
->r
);
4673 *y
= SIZE(params
->c
* params
->r
);
4676 static void game_set_size(drawing
*dr
, game_drawstate
*ds
,
4677 game_params
*params
, int tilesize
)
4679 ds
->tilesize
= tilesize
;
4682 static float *game_colours(frontend
*fe
, int *ncolours
)
4684 float *ret
= snewn(3 * NCOLOURS
, float);
4686 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
4688 ret
[COL_XDIAGONALS
* 3 + 0] = 0.9F
* ret
[COL_BACKGROUND
* 3 + 0];
4689 ret
[COL_XDIAGONALS
* 3 + 1] = 0.9F
* ret
[COL_BACKGROUND
* 3 + 1];
4690 ret
[COL_XDIAGONALS
* 3 + 2] = 0.9F
* ret
[COL_BACKGROUND
* 3 + 2];
4692 ret
[COL_GRID
* 3 + 0] = 0.0F
;
4693 ret
[COL_GRID
* 3 + 1] = 0.0F
;
4694 ret
[COL_GRID
* 3 + 2] = 0.0F
;
4696 ret
[COL_CLUE
* 3 + 0] = 0.0F
;
4697 ret
[COL_CLUE
* 3 + 1] = 0.0F
;
4698 ret
[COL_CLUE
* 3 + 2] = 0.0F
;
4700 ret
[COL_USER
* 3 + 0] = 0.0F
;
4701 ret
[COL_USER
* 3 + 1] = 0.6F
* ret
[COL_BACKGROUND
* 3 + 1];
4702 ret
[COL_USER
* 3 + 2] = 0.0F
;
4704 ret
[COL_HIGHLIGHT
* 3 + 0] = 0.78F
* ret
[COL_BACKGROUND
* 3 + 0];
4705 ret
[COL_HIGHLIGHT
* 3 + 1] = 0.78F
* ret
[COL_BACKGROUND
* 3 + 1];
4706 ret
[COL_HIGHLIGHT
* 3 + 2] = 0.78F
* ret
[COL_BACKGROUND
* 3 + 2];
4708 ret
[COL_ERROR
* 3 + 0] = 1.0F
;
4709 ret
[COL_ERROR
* 3 + 1] = 0.0F
;
4710 ret
[COL_ERROR
* 3 + 2] = 0.0F
;
4712 ret
[COL_PENCIL
* 3 + 0] = 0.5F
* ret
[COL_BACKGROUND
* 3 + 0];
4713 ret
[COL_PENCIL
* 3 + 1] = 0.5F
* ret
[COL_BACKGROUND
* 3 + 1];
4714 ret
[COL_PENCIL
* 3 + 2] = ret
[COL_BACKGROUND
* 3 + 2];
4716 ret
[COL_KILLER
* 3 + 0] = 0.5F
* ret
[COL_BACKGROUND
* 3 + 0];
4717 ret
[COL_KILLER
* 3 + 1] = 0.5F
* ret
[COL_BACKGROUND
* 3 + 1];
4718 ret
[COL_KILLER
* 3 + 2] = 0.1F
* ret
[COL_BACKGROUND
* 3 + 2];
4720 *ncolours
= NCOLOURS
;
4724 static game_drawstate
*game_new_drawstate(drawing
*dr
, game_state
*state
)
4726 struct game_drawstate
*ds
= snew(struct game_drawstate
);
4729 ds
->started
= FALSE
;
4731 ds
->xtype
= state
->xtype
;
4732 ds
->grid
= snewn(cr
*cr
, digit
);
4733 memset(ds
->grid
, cr
+2, cr
*cr
);
4734 ds
->pencil
= snewn(cr
*cr
*cr
, digit
);
4735 memset(ds
->pencil
, 0, cr
*cr
*cr
);
4736 ds
->hl
= snewn(cr
*cr
, unsigned char);
4737 memset(ds
->hl
, 0, cr
*cr
);
4739 * ds->entered_items needs one row of cr entries per entity in
4740 * which digits may not be duplicated. That's one for each row,
4741 * each column, each block, each diagonal, and each Killer cage.
4743 ds
->nregions
= cr
*3 + 2;
4745 ds
->nregions
+= state
->kblocks
->nr_blocks
;
4746 ds
->entered_items
= snewn(cr
* ds
->nregions
, int);
4747 ds
->tilesize
= 0; /* not decided yet */
4751 static void game_free_drawstate(drawing
*dr
, game_drawstate
*ds
)
4756 sfree(ds
->entered_items
);
4760 static void draw_number(drawing
*dr
, game_drawstate
*ds
, game_state
*state
,
4761 int x
, int y
, int hl
)
4766 int col_killer
= (hl
& 32 ? COL_ERROR
: COL_KILLER
);
4769 if (ds
->grid
[y
*cr
+x
] == state
->grid
[y
*cr
+x
] &&
4770 ds
->hl
[y
*cr
+x
] == hl
&&
4771 !memcmp(ds
->pencil
+(y
*cr
+x
)*cr
, state
->pencil
+(y
*cr
+x
)*cr
, cr
))
4772 return; /* no change required */
4774 tx
= BORDER
+ x
* TILE_SIZE
+ 1 + GRIDEXTRA
;
4775 ty
= BORDER
+ y
* TILE_SIZE
+ 1 + GRIDEXTRA
;
4779 cw
= tw
= TILE_SIZE
-1-2*GRIDEXTRA
;
4780 ch
= th
= TILE_SIZE
-1-2*GRIDEXTRA
;
4782 if (x
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[y
*cr
+x
-1])
4783 cx
-= GRIDEXTRA
, cw
+= GRIDEXTRA
;
4784 if (x
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[y
*cr
+x
+1])
4786 if (y
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[(y
-1)*cr
+x
])
4787 cy
-= GRIDEXTRA
, ch
+= GRIDEXTRA
;
4788 if (y
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[(y
+1)*cr
+x
])
4791 clip(dr
, cx
, cy
, cw
, ch
);
4793 /* background needs erasing */
4794 draw_rect(dr
, cx
, cy
, cw
, ch
,
4795 ((hl
& 15) == 1 ? COL_HIGHLIGHT
:
4796 (ds
->xtype
&& (ondiag0(y
*cr
+x
) || ondiag1(y
*cr
+x
))) ? COL_XDIAGONALS
:
4800 * Draw the corners of thick lines in corner-adjacent squares,
4801 * which jut into this square by one pixel.
4803 if (x
> 0 && y
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
-1)*cr
+x
-1])
4804 draw_rect(dr
, tx
-GRIDEXTRA
, ty
-GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
4805 if (x
+1 < cr
&& y
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
-1)*cr
+x
+1])
4806 draw_rect(dr
, tx
+TILE_SIZE
-1-2*GRIDEXTRA
, ty
-GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
4807 if (x
> 0 && y
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
+1)*cr
+x
-1])
4808 draw_rect(dr
, tx
-GRIDEXTRA
, ty
+TILE_SIZE
-1-2*GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
4809 if (x
+1 < cr
&& y
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
+1)*cr
+x
+1])
4810 draw_rect(dr
, tx
+TILE_SIZE
-1-2*GRIDEXTRA
, ty
+TILE_SIZE
-1-2*GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
4812 /* pencil-mode highlight */
4813 if ((hl
& 15) == 2) {
4817 coords
[2] = cx
+cw
/2;
4820 coords
[5] = cy
+ch
/2;
4821 draw_polygon(dr
, coords
, 3, COL_HIGHLIGHT
, COL_HIGHLIGHT
);
4824 if (state
->kblocks
) {
4825 int t
= GRIDEXTRA
* 3;
4826 int kcx
, kcy
, kcw
, kch
;
4828 int has_left
= 0, has_right
= 0, has_top
= 0, has_bottom
= 0;
4831 * In non-jigsaw mode, the Killer cages are placed at a
4832 * fixed offset from the outer edge of the cell dividing
4833 * lines, so that they look right whether those lines are
4834 * thick or thin. In jigsaw mode, however, doing this will
4835 * sometimes cause the cage outlines in adjacent squares to
4836 * fail to match up with each other, so we must offset a
4837 * fixed amount from the _centre_ of the cell dividing
4840 if (state
->blocks
->r
== 1) {
4857 * First, draw the lines dividing this area from neighbouring
4860 if (x
== 0 || state
->kblocks
->whichblock
[y
*cr
+x
] != state
->kblocks
->whichblock
[y
*cr
+x
-1])
4861 has_left
= 1, kl
+= t
;
4862 if (x
+1 >= cr
|| state
->kblocks
->whichblock
[y
*cr
+x
] != state
->kblocks
->whichblock
[y
*cr
+x
+1])
4863 has_right
= 1, kr
-= t
;
4864 if (y
== 0 || state
->kblocks
->whichblock
[y
*cr
+x
] != state
->kblocks
->whichblock
[(y
-1)*cr
+x
])
4865 has_top
= 1, kt
+= t
;
4866 if (y
+1 >= cr
|| state
->kblocks
->whichblock
[y
*cr
+x
] != state
->kblocks
->whichblock
[(y
+1)*cr
+x
])
4867 has_bottom
= 1, kb
-= t
;
4869 draw_line(dr
, kl
, kt
, kr
, kt
, col_killer
);
4871 draw_line(dr
, kl
, kb
, kr
, kb
, col_killer
);
4873 draw_line(dr
, kl
, kt
, kl
, kb
, col_killer
);
4875 draw_line(dr
, kr
, kt
, kr
, kb
, col_killer
);
4877 * Now, take care of the corners (just as for the normal borders).
4878 * We only need a corner if there wasn't a full edge.
4880 if (x
> 0 && y
> 0 && !has_left
&& !has_top
4881 && state
->kblocks
->whichblock
[y
*cr
+x
] != state
->kblocks
->whichblock
[(y
-1)*cr
+x
-1])
4883 draw_line(dr
, kl
, kt
+ t
, kl
+ t
, kt
+ t
, col_killer
);
4884 draw_line(dr
, kl
+ t
, kt
, kl
+ t
, kt
+ t
, col_killer
);
4886 if (x
+1 < cr
&& y
> 0 && !has_right
&& !has_top
4887 && state
->kblocks
->whichblock
[y
*cr
+x
] != state
->kblocks
->whichblock
[(y
-1)*cr
+x
+1])
4889 draw_line(dr
, kcx
+ kcw
- t
, kt
+ t
, kcx
+ kcw
, kt
+ t
, col_killer
);
4890 draw_line(dr
, kcx
+ kcw
- t
, kt
, kcx
+ kcw
- t
, kt
+ t
, col_killer
);
4892 if (x
> 0 && y
+1 < cr
&& !has_left
&& !has_bottom
4893 && state
->kblocks
->whichblock
[y
*cr
+x
] != state
->kblocks
->whichblock
[(y
+1)*cr
+x
-1])
4895 draw_line(dr
, kl
, kcy
+ kch
- t
, kl
+ t
, kcy
+ kch
- t
, col_killer
);
4896 draw_line(dr
, kl
+ t
, kcy
+ kch
- t
, kl
+ t
, kcy
+ kch
, col_killer
);
4898 if (x
+1 < cr
&& y
+1 < cr
&& !has_right
&& !has_bottom
4899 && state
->kblocks
->whichblock
[y
*cr
+x
] != state
->kblocks
->whichblock
[(y
+1)*cr
+x
+1])
4901 draw_line(dr
, kcx
+ kcw
- t
, kcy
+ kch
- t
, kcx
+ kcw
- t
, kcy
+ kch
, col_killer
);
4902 draw_line(dr
, kcx
+ kcw
- t
, kcy
+ kch
- t
, kcx
+ kcw
, kcy
+ kch
- t
, col_killer
);
4907 if (state
->killer
&& state
->kgrid
[y
*cr
+x
]) {
4908 sprintf (str
, "%d", state
->kgrid
[y
*cr
+x
]);
4909 draw_text(dr
, tx
+ GRIDEXTRA
* 4, ty
+ GRIDEXTRA
* 4 + TILE_SIZE
/4,
4910 FONT_VARIABLE
, TILE_SIZE
/4, ALIGN_VNORMAL
| ALIGN_HLEFT
,
4914 /* new number needs drawing? */
4915 if (state
->grid
[y
*cr
+x
]) {
4917 str
[0] = state
->grid
[y
*cr
+x
] + '0';
4919 str
[0] += 'a' - ('9'+1);
4920 draw_text(dr
, tx
+ TILE_SIZE
/2, ty
+ TILE_SIZE
/2,
4921 FONT_VARIABLE
, TILE_SIZE
/2, ALIGN_VCENTRE
| ALIGN_HCENTRE
,
4922 state
->immutable
[y
*cr
+x
] ? COL_CLUE
: (hl
& 16) ? COL_ERROR
: COL_USER
, str
);
4927 int pw
, ph
, minph
, pbest
, fontsize
;
4929 /* Count the pencil marks required. */
4930 for (i
= npencil
= 0; i
< cr
; i
++)
4931 if (state
->pencil
[(y
*cr
+x
)*cr
+i
])
4938 * Determine the bounding rectangle within which we're going
4939 * to put the pencil marks.
4941 /* Start with the whole square */
4942 pl
= tx
+ GRIDEXTRA
;
4943 pr
= pl
+ TILE_SIZE
- GRIDEXTRA
;
4944 pt
= ty
+ GRIDEXTRA
;
4945 pb
= pt
+ TILE_SIZE
- GRIDEXTRA
;
4946 if (state
->killer
) {
4948 * Make space for the Killer cages. We do this
4949 * unconditionally, for uniformity between squares,
4950 * rather than making it depend on whether a Killer
4951 * cage edge is actually present on any given side.
4953 pl
+= GRIDEXTRA
* 3;
4954 pr
-= GRIDEXTRA
* 3;
4955 pt
+= GRIDEXTRA
* 3;
4956 pb
-= GRIDEXTRA
* 3;
4957 if (state
->kgrid
[y
*cr
+x
] != 0) {
4958 /* Make further space for the Killer number. */
4965 * We arrange our pencil marks in a grid layout, with
4966 * the number of rows and columns adjusted to allow the
4967 * maximum font size.
4969 * So now we work out what the grid size ought to be.
4974 for (pw
= 3; pw
< max(npencil
,4); pw
++) {
4977 ph
= (npencil
+ pw
- 1) / pw
;
4978 ph
= max(ph
, minph
);
4979 fw
= (pr
- pl
) / (float)pw
;
4980 fh
= (pb
- pt
) / (float)ph
;
4982 if (fs
> bestsize
) {
4989 ph
= (npencil
+ pw
- 1) / pw
;
4990 ph
= max(ph
, minph
);
4993 * Now we've got our grid dimensions, work out the pixel
4994 * size of a grid element, and round it to the nearest
4995 * pixel. (We don't want rounding errors to make the
4996 * grid look uneven at low pixel sizes.)
4998 fontsize
= min((pr
- pl
) / pw
, (pb
- pt
) / ph
);
5001 * Centre the resulting figure in the square.
5003 pl
= tx
+ (TILE_SIZE
- fontsize
* pw
) / 2;
5004 pt
= ty
+ (TILE_SIZE
- fontsize
* ph
) / 2;
5007 * And move it down a bit if it's collided with the
5008 * Killer cage number.
5010 if (state
->killer
&& state
->kgrid
[y
*cr
+x
] != 0) {
5011 pt
= max(pt
, ty
+ GRIDEXTRA
* 3 + TILE_SIZE
/4);
5015 * Now actually draw the pencil marks.
5017 for (i
= j
= 0; i
< cr
; i
++)
5018 if (state
->pencil
[(y
*cr
+x
)*cr
+i
]) {
5019 int dx
= j
% pw
, dy
= j
/ pw
;
5024 str
[0] += 'a' - ('9'+1);
5025 draw_text(dr
, pl
+ fontsize
* (2*dx
+1) / 2,
5026 pt
+ fontsize
* (2*dy
+1) / 2,
5027 FONT_VARIABLE
, fontsize
,
5028 ALIGN_VCENTRE
| ALIGN_HCENTRE
, COL_PENCIL
, str
);
5036 draw_update(dr
, cx
, cy
, cw
, ch
);
5038 ds
->grid
[y
*cr
+x
] = state
->grid
[y
*cr
+x
];
5039 memcpy(ds
->pencil
+(y
*cr
+x
)*cr
, state
->pencil
+(y
*cr
+x
)*cr
, cr
);
5040 ds
->hl
[y
*cr
+x
] = hl
;
5043 static void game_redraw(drawing
*dr
, game_drawstate
*ds
, game_state
*oldstate
,
5044 game_state
*state
, int dir
, game_ui
*ui
,
5045 float animtime
, float flashtime
)
5052 * The initial contents of the window are not guaranteed
5053 * and can vary with front ends. To be on the safe side,
5054 * all games should start by drawing a big
5055 * background-colour rectangle covering the whole window.
5057 draw_rect(dr
, 0, 0, SIZE(cr
), SIZE(cr
), COL_BACKGROUND
);
5060 * Draw the grid. We draw it as a big thick rectangle of
5061 * COL_GRID initially; individual calls to draw_number()
5062 * will poke the right-shaped holes in it.
5064 draw_rect(dr
, BORDER
-GRIDEXTRA
, BORDER
-GRIDEXTRA
,
5065 cr
*TILE_SIZE
+1+2*GRIDEXTRA
, cr
*TILE_SIZE
+1+2*GRIDEXTRA
,
5070 * This array is used to keep track of rows, columns and boxes
5071 * which contain a number more than once.
5073 for (x
= 0; x
< cr
* ds
->nregions
; x
++)
5074 ds
->entered_items
[x
] = 0;
5075 for (x
= 0; x
< cr
; x
++)
5076 for (y
= 0; y
< cr
; y
++) {
5077 digit d
= state
->grid
[y
*cr
+x
];
5082 ds
->entered_items
[x
*cr
+d
-1]++;
5085 ds
->entered_items
[(y
+cr
)*cr
+d
-1]++;
5088 box
= state
->blocks
->whichblock
[y
*cr
+x
];
5089 ds
->entered_items
[(box
+2*cr
)*cr
+d
-1]++;
5093 if (ondiag0(y
*cr
+x
))
5094 ds
->entered_items
[(3*cr
)*cr
+d
-1]++;
5095 if (ondiag1(y
*cr
+x
))
5096 ds
->entered_items
[(3*cr
+1)*cr
+d
-1]++;
5100 if (state
->kblocks
) {
5101 kbox
= state
->kblocks
->whichblock
[y
*cr
+x
];
5102 ds
->entered_items
[(kbox
+3*cr
+2)*cr
+d
-1]++;
5108 * Draw any numbers which need redrawing.
5110 for (x
= 0; x
< cr
; x
++) {
5111 for (y
= 0; y
< cr
; y
++) {
5113 digit d
= state
->grid
[y
*cr
+x
];
5115 if (flashtime
> 0 &&
5116 (flashtime
<= FLASH_TIME
/3 ||
5117 flashtime
>= FLASH_TIME
*2/3))
5120 /* Highlight active input areas. */
5121 if (x
== ui
->hx
&& y
== ui
->hy
&& ui
->hshow
)
5122 highlight
= ui
->hpencil
? 2 : 1;
5124 /* Mark obvious errors (ie, numbers which occur more than once
5125 * in a single row, column, or box). */
5126 if (d
&& (ds
->entered_items
[x
*cr
+d
-1] > 1 ||
5127 ds
->entered_items
[(y
+cr
)*cr
+d
-1] > 1 ||
5128 ds
->entered_items
[(state
->blocks
->whichblock
[y
*cr
+x
]
5129 +2*cr
)*cr
+d
-1] > 1 ||
5130 (ds
->xtype
&& ((ondiag0(y
*cr
+x
) &&
5131 ds
->entered_items
[(3*cr
)*cr
+d
-1] > 1) ||
5133 ds
->entered_items
[(3*cr
+1)*cr
+d
-1]>1)))||
5135 ds
->entered_items
[(state
->kblocks
->whichblock
[y
*cr
+x
]
5136 +3*cr
+2)*cr
+d
-1] > 1)))
5139 if (d
&& state
->kblocks
) {
5140 int i
, b
= state
->kblocks
->whichblock
[y
*cr
+x
];
5141 int n_squares
= state
->kblocks
->nr_squares
[b
];
5142 int sum
= 0, clue
= 0;
5143 for (i
= 0; i
< n_squares
; i
++) {
5144 int xy
= state
->kblocks
->blocks
[b
][i
];
5145 if (state
->grid
[xy
] == 0)
5148 sum
+= state
->grid
[xy
];
5149 if (state
->kgrid
[xy
]) {
5151 clue
= state
->kgrid
[xy
];
5155 if (i
== n_squares
) {
5162 draw_number(dr
, ds
, state
, x
, y
, highlight
);
5167 * Update the _entire_ grid if necessary.
5170 draw_update(dr
, 0, 0, SIZE(cr
), SIZE(cr
));
5175 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
5176 int dir
, game_ui
*ui
)
5181 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
5182 int dir
, game_ui
*ui
)
5184 if (!oldstate
->completed
&& newstate
->completed
&&
5185 !oldstate
->cheated
&& !newstate
->cheated
)
5190 static int game_status(game_state
*state
)
5192 return state
->completed
? +1 : 0;
5195 static int game_timing_state(game_state
*state
, game_ui
*ui
)
5197 if (state
->completed
)
5202 static void game_print_size(game_params
*params
, float *x
, float *y
)
5207 * I'll use 9mm squares by default. They should be quite big
5208 * for this game, because players will want to jot down no end
5209 * of pencil marks in the squares.
5211 game_compute_size(params
, 900, &pw
, &ph
);
5217 * Subfunction to draw the thick lines between cells. In order to do
5218 * this using the line-drawing rather than rectangle-drawing API (so
5219 * as to get line thicknesses to scale correctly) and yet have
5220 * correctly mitred joins between lines, we must do this by tracing
5221 * the boundary of each sub-block and drawing it in one go as a
5224 * This subfunction is also reused with thinner dotted lines to
5225 * outline the Killer cages, this time offsetting the outline toward
5226 * the interior of the affected squares.
5228 static void outline_block_structure(drawing
*dr
, game_drawstate
*ds
,
5230 struct block_structure
*blocks
,
5236 int x
, y
, dx
, dy
, sx
, sy
, sdx
, sdy
;
5239 * Maximum perimeter of a k-omino is 2k+2. (Proof: start
5240 * with k unconnected squares, with total perimeter 4k.
5241 * Now repeatedly join two disconnected components
5242 * together into a larger one; every time you do so you
5243 * remove at least two unit edges, and you require k-1 of
5244 * these operations to create a single connected piece, so
5245 * you must have at most 4k-2(k-1) = 2k+2 unit edges left
5248 coords
= snewn(4*cr
+4, int); /* 2k+2 points, 2 coords per point */
5251 * Iterate over all the blocks.
5253 for (bi
= 0; bi
< blocks
->nr_blocks
; bi
++) {
5254 if (blocks
->nr_squares
[bi
] == 0)
5258 * For each block, find a starting square within it
5259 * which has a boundary at the left.
5261 for (i
= 0; i
< cr
; i
++) {
5262 int j
= blocks
->blocks
[bi
][i
];
5263 if (j
% cr
== 0 || blocks
->whichblock
[j
-1] != bi
)
5266 assert(i
< cr
); /* every block must have _some_ leftmost square */
5267 x
= blocks
->blocks
[bi
][i
] % cr
;
5268 y
= blocks
->blocks
[bi
][i
] / cr
;
5273 * Now begin tracing round the perimeter. At all
5274 * times, (x,y) describes some square within the
5275 * block, and (x+dx,y+dy) is some adjacent square
5276 * outside it; so the edge between those two squares
5277 * is always an edge of the block.
5279 sx
= x
, sy
= y
, sdx
= dx
, sdy
= dy
; /* save starting position */
5282 int cx
, cy
, tx
, ty
, nin
;
5285 * Advance to the next edge, by looking at the two
5286 * squares beyond it. If they're both outside the block,
5287 * we turn right (by leaving x,y the same and rotating
5288 * dx,dy clockwise); if they're both inside, we turn
5289 * left (by rotating dx,dy anticlockwise and contriving
5290 * to leave x+dx,y+dy unchanged); if one of each, we go
5291 * straight on (and may enforce by assertion that
5292 * they're one of each the _right_ way round).
5297 nin
+= (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
&&
5298 blocks
->whichblock
[ty
*cr
+tx
] == bi
);
5301 nin
+= (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
&&
5302 blocks
->whichblock
[ty
*cr
+tx
] == bi
);
5311 } else if (nin
== 2) {
5335 * Now enforce by assertion that we ended up
5336 * somewhere sensible.
5338 assert(x
>= 0 && x
< cr
&& y
>= 0 && y
< cr
&&
5339 blocks
->whichblock
[y
*cr
+x
] == bi
);
5340 assert(x
+dx
< 0 || x
+dx
>= cr
|| y
+dy
< 0 || y
+dy
>= cr
||
5341 blocks
->whichblock
[(y
+dy
)*cr
+(x
+dx
)] != bi
);
5344 * Record the point we just went past at one end of the
5345 * edge. To do this, we translate (x,y) down and right
5346 * by half a unit (so they're describing a point in the
5347 * _centre_ of the square) and then translate back again
5348 * in a manner rotated by dy and dx.
5351 cx
= ((2*x
+1) + dy
+ dx
) / 2;
5352 cy
= ((2*y
+1) - dx
+ dy
) / 2;
5353 coords
[2*n
+0] = BORDER
+ cx
* TILE_SIZE
;
5354 coords
[2*n
+1] = BORDER
+ cy
* TILE_SIZE
;
5355 coords
[2*n
+0] -= dx
* inset
;
5356 coords
[2*n
+1] -= dy
* inset
;
5359 * We turned right, so inset this corner back along
5360 * the edge towards the centre of the square.
5362 coords
[2*n
+0] -= dy
* inset
;
5363 coords
[2*n
+1] += dx
* inset
;
5364 } else if (nin
== 2) {
5366 * We turned left, so inset this corner further
5367 * _out_ along the edge into the next square.
5369 coords
[2*n
+0] += dy
* inset
;
5370 coords
[2*n
+1] -= dx
* inset
;
5374 } while (x
!= sx
|| y
!= sy
|| dx
!= sdx
|| dy
!= sdy
);
5377 * That's our polygon; now draw it.
5379 draw_polygon(dr
, coords
, n
, -1, ink
);
5385 static void game_print(drawing
*dr
, game_state
*state
, int tilesize
)
5388 int ink
= print_mono_colour(dr
, 0);
5391 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
5392 game_drawstate ads
, *ds
= &ads
;
5393 game_set_size(dr
, ds
, NULL
, tilesize
);
5398 print_line_width(dr
, 3 * TILE_SIZE
/ 40);
5399 draw_rect_outline(dr
, BORDER
, BORDER
, cr
*TILE_SIZE
, cr
*TILE_SIZE
, ink
);
5402 * Highlight X-diagonal squares.
5406 int xhighlight
= print_grey_colour(dr
, 0.90F
);
5408 for (i
= 0; i
< cr
; i
++)
5409 draw_rect(dr
, BORDER
+ i
*TILE_SIZE
, BORDER
+ i
*TILE_SIZE
,
5410 TILE_SIZE
, TILE_SIZE
, xhighlight
);
5411 for (i
= 0; i
< cr
; i
++)
5412 if (i
*2 != cr
-1) /* avoid redoing centre square, just for fun */
5413 draw_rect(dr
, BORDER
+ i
*TILE_SIZE
,
5414 BORDER
+ (cr
-1-i
)*TILE_SIZE
,
5415 TILE_SIZE
, TILE_SIZE
, xhighlight
);
5421 for (x
= 1; x
< cr
; x
++) {
5422 print_line_width(dr
, TILE_SIZE
/ 40);
5423 draw_line(dr
, BORDER
+x
*TILE_SIZE
, BORDER
,
5424 BORDER
+x
*TILE_SIZE
, BORDER
+cr
*TILE_SIZE
, ink
);
5426 for (y
= 1; y
< cr
; y
++) {
5427 print_line_width(dr
, TILE_SIZE
/ 40);
5428 draw_line(dr
, BORDER
, BORDER
+y
*TILE_SIZE
,
5429 BORDER
+cr
*TILE_SIZE
, BORDER
+y
*TILE_SIZE
, ink
);
5433 * Thick lines between cells.
5435 print_line_width(dr
, 3 * TILE_SIZE
/ 40);
5436 outline_block_structure(dr
, ds
, state
, state
->blocks
, ink
, 0);
5439 * Killer cages and their totals.
5441 if (state
->kblocks
) {
5442 print_line_width(dr
, TILE_SIZE
/ 40);
5443 print_line_dotted(dr
, TRUE
);
5444 outline_block_structure(dr
, ds
, state
, state
->kblocks
, ink
,
5445 5 * TILE_SIZE
/ 40);
5446 print_line_dotted(dr
, FALSE
);
5447 for (y
= 0; y
< cr
; y
++)
5448 for (x
= 0; x
< cr
; x
++)
5449 if (state
->kgrid
[y
*cr
+x
]) {
5451 sprintf(str
, "%d", state
->kgrid
[y
*cr
+x
]);
5453 BORDER
+x
*TILE_SIZE
+ 7*TILE_SIZE
/40,
5454 BORDER
+y
*TILE_SIZE
+ 16*TILE_SIZE
/40,
5455 FONT_VARIABLE
, TILE_SIZE
/4,
5456 ALIGN_VNORMAL
| ALIGN_HLEFT
,
5462 * Standard (non-Killer) clue numbers.
5464 for (y
= 0; y
< cr
; y
++)
5465 for (x
= 0; x
< cr
; x
++)
5466 if (state
->grid
[y
*cr
+x
]) {
5469 str
[0] = state
->grid
[y
*cr
+x
] + '0';
5471 str
[0] += 'a' - ('9'+1);
5472 draw_text(dr
, BORDER
+ x
*TILE_SIZE
+ TILE_SIZE
/2,
5473 BORDER
+ y
*TILE_SIZE
+ TILE_SIZE
/2,
5474 FONT_VARIABLE
, TILE_SIZE
/2,
5475 ALIGN_VCENTRE
| ALIGN_HCENTRE
, ink
, str
);
5480 #define thegame solo
5483 const struct game thegame
= {
5484 "Solo", "games.solo", "solo",
5491 TRUE
, game_configure
, custom_params
,
5499 TRUE
, game_can_format_as_text_now
, game_text_format
,
5507 PREFERRED_TILE_SIZE
, game_compute_size
, game_set_size
,
5510 game_free_drawstate
,
5515 TRUE
, FALSE
, game_print_size
, game_print
,
5516 FALSE
, /* wants_statusbar */
5517 FALSE
, game_timing_state
,
5518 REQUIRE_RBUTTON
| REQUIRE_NUMPAD
, /* flags */
5521 #ifdef STANDALONE_SOLVER
5523 int main(int argc
, char **argv
)
5527 char *id
= NULL
, *desc
, *err
;
5529 struct difficulty dlev
;
5531 while (--argc
> 0) {
5533 if (!strcmp(p
, "-v")) {
5534 solver_show_working
= TRUE
;
5535 } else if (!strcmp(p
, "-g")) {
5537 } else if (*p
== '-') {
5538 fprintf(stderr
, "%s: unrecognised option `%s'\n", argv
[0], p
);
5546 fprintf(stderr
, "usage: %s [-g | -v] <game_id>\n", argv
[0]);
5550 desc
= strchr(id
, ':');
5552 fprintf(stderr
, "%s: game id expects a colon in it\n", argv
[0]);
5557 p
= default_params();
5558 decode_params(p
, id
);
5559 err
= validate_desc(p
, desc
);
5561 fprintf(stderr
, "%s: %s\n", argv
[0], err
);
5564 s
= new_game(NULL
, p
, desc
);
5566 dlev
.maxdiff
= DIFF_RECURSIVE
;
5567 dlev
.maxkdiff
= DIFF_KINTERSECT
;
5568 solver(s
->cr
, s
->blocks
, s
->kblocks
, s
->xtype
, s
->grid
, s
->kgrid
, &dlev
);
5570 printf("Difficulty rating: %s\n",
5571 dlev
.diff
==DIFF_BLOCK
? "Trivial (blockwise positional elimination only)":
5572 dlev
.diff
==DIFF_SIMPLE
? "Basic (row/column/number elimination required)":
5573 dlev
.diff
==DIFF_INTERSECT
? "Intermediate (intersectional analysis required)":
5574 dlev
.diff
==DIFF_SET
? "Advanced (set elimination required)":
5575 dlev
.diff
==DIFF_EXTREME
? "Extreme (complex non-recursive techniques required)":
5576 dlev
.diff
==DIFF_RECURSIVE
? "Unreasonable (guesswork and backtracking required)":
5577 dlev
.diff
==DIFF_AMBIGUOUS
? "Ambiguous (multiple solutions exist)":
5578 dlev
.diff
==DIFF_IMPOSSIBLE
? "Impossible (no solution exists)":
5579 "INTERNAL ERROR: unrecognised difficulty code");
5581 printf("Killer difficulty: %s\n",
5582 dlev
.kdiff
==DIFF_KSINGLE
? "Trivial (single square cages only)":
5583 dlev
.kdiff
==DIFF_KMINMAX
? "Simple (maximum sum analysis required)":
5584 dlev
.kdiff
==DIFF_KSUMS
? "Intermediate (sum possibilities)":
5585 dlev
.kdiff
==DIFF_KINTERSECT
? "Advanced (sum region intersections)":
5586 "INTERNAL ERROR: unrecognised difficulty code");
5588 printf("%s\n", grid_text_format(s
->cr
, s
->blocks
, s
->xtype
, s
->grid
));
5596 /* vim: set shiftwidth=4 tabstop=8: */