2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
6 * - Jigsaw Sudoku is currently an undocumented feature enabled
7 * by setting r (`Rows of sub-blocks' in the GUI configurer) to
8 * 1. The reason it's undocumented is because they're rather
9 * erratic to generate, because gridgen tends to hang up for
10 * ages. I think this is because some jigsaw block layouts
11 * simply do not admit very many valid filled grids (and
12 * perhaps some have none at all).
13 * + To fix this, I think probably the solution is a change in
14 * grid generation policy: gridgen needs to have less of an
15 * all-or-nothing attitude and instead make only a limited
16 * amount of effort to construct a filled grid before giving
17 * up and trying a new layout. (Come to think of it, this
18 * same change might also make 5x5 standard Sudoku more
19 * practical to generate, if correctly tuned.)
20 * + If I get this fixed, other work needed on jigsaw mode is:
21 * * introduce a GUI config checkbox. game_configure()
22 * ticks this box iff r==1; if it's ticked in a call to
23 * custom_params(), we replace (c, r) with (c*r, 1).
26 * - reports from users are that `Trivial'-mode puzzles are still
27 * rather hard compared to newspapers' easy ones, so some better
28 * low-end difficulty grading would be nice
29 * + it's possible that really easy puzzles always have
30 * _several_ things you can do, so don't make you hunt too
31 * hard for the one deduction you can currently make
32 * + it's also possible that easy puzzles require fewer
33 * cross-eliminations: perhaps there's a higher incidence of
34 * things you can deduce by looking only at (say) rows,
35 * rather than things you have to check both rows and columns
37 * + but really, what I need to do is find some really easy
38 * puzzles and _play_ them, to see what's actually easy about
40 * + while I'm revamping this area, filling in the _last_
41 * number in a nearly-full row or column should certainly be
42 * permitted even at the lowest difficulty level.
43 * + also Owen noticed that `Basic' grids requiring numeric
44 * elimination are actually very hard, so I wonder if a
45 * difficulty gradation between that and positional-
46 * elimination-only might be in order
47 * + but it's not good to have _too_ many difficulty levels, or
48 * it'll take too long to randomly generate a given level.
50 * - it might still be nice to do some prioritisation on the
51 * removal of numbers from the grid
52 * + one possibility is to try to minimise the maximum number
53 * of filled squares in any block, which in particular ought
54 * to enforce never leaving a completely filled block in the
55 * puzzle as presented.
57 * - alternative interface modes
58 * + sudoku.com's Windows program has a palette of possible
59 * entries; you select a palette entry first and then click
60 * on the square you want it to go in, thus enabling
61 * mouse-only play. Useful for PDAs! I don't think it's
62 * actually incompatible with the current highlight-then-type
63 * approach: you _either_ highlight a palette entry and then
64 * click, _or_ you highlight a square and then type. At most
65 * one thing is ever highlighted at a time, so there's no way
67 * + then again, I don't actually like sudoku.com's interface;
68 * it's too much like a paint package whereas I prefer to
69 * think of Solo as a text editor.
70 * + another PDA-friendly possibility is a drag interface:
71 * _drag_ numbers from the palette into the grid squares.
72 * Thought experiments suggest I'd prefer that to the
73 * sudoku.com approach, but I haven't actually tried it.
77 * Solo puzzles need to be square overall (since each row and each
78 * column must contain one of every digit), but they need not be
79 * subdivided the same way internally. I am going to adopt a
80 * convention whereby I _always_ refer to `r' as the number of rows
81 * of _big_ divisions, and `c' as the number of columns of _big_
82 * divisions. Thus, a 2c by 3r puzzle looks something like this:
86 * ------+------ (Of course, you can't subdivide it the other way
87 * 1 4 5 | 6 3 2 or you'll get clashes; observe that the 4 in the
88 * 3 2 6 | 4 1 5 top left would conflict with the 4 in the second
89 * ------+------ box down on the left-hand side.)
93 * The need for a strong naming convention should now be clear:
94 * each small box is two rows of digits by three columns, while the
95 * overall puzzle has three rows of small boxes by two columns. So
96 * I will (hopefully) consistently use `r' to denote the number of
97 * rows _of small boxes_ (here 3), which is also the number of
98 * columns of digits in each small box; and `c' vice versa (here
101 * I'm also going to choose arbitrarily to list c first wherever
102 * possible: the above is a 2x3 puzzle, not a 3x2 one.
112 #ifdef STANDALONE_SOLVER
114 int solver_show_working
, solver_recurse_depth
;
120 * To save space, I store digits internally as unsigned char. This
121 * imposes a hard limit of 255 on the order of the puzzle. Since
122 * even a 5x5 takes unacceptably long to generate, I don't see this
123 * as a serious limitation unless something _really_ impressive
124 * happens in computing technology; but here's a typedef anyway for
125 * general good practice.
127 typedef unsigned char digit
;
128 #define ORDER_MAX 255
130 #define PREFERRED_TILE_SIZE 32
131 #define TILE_SIZE (ds->tilesize)
132 #define BORDER (TILE_SIZE / 2)
133 #define GRIDEXTRA (TILE_SIZE / 32)
135 #define FLASH_TIME 0.4F
137 enum { SYMM_NONE
, SYMM_ROT2
, SYMM_ROT4
, SYMM_REF2
, SYMM_REF2D
, SYMM_REF4
,
138 SYMM_REF4D
, SYMM_REF8
};
140 enum { DIFF_BLOCK
, DIFF_SIMPLE
, DIFF_INTERSECT
, DIFF_SET
, DIFF_EXTREME
,
141 DIFF_RECURSIVE
, DIFF_AMBIGUOUS
, DIFF_IMPOSSIBLE
};
157 * For a square puzzle, `c' and `r' indicate the puzzle
158 * parameters as described above.
160 * A jigsaw-style puzzle is indicated by r==1, in which case c
161 * can be whatever it likes (there is no constraint on
162 * compositeness - a 7x7 jigsaw sudoku makes perfect sense).
164 int c
, r
, symm
, diff
;
165 int xtype
; /* require all digits in X-diagonals */
168 struct block_structure
{
172 * For text formatting, we do need c and r here.
177 * For any square index, whichblock[i] gives its block index.
179 * For 0 <= b,i < cr, blocks[b][i] gives the index of the ith
182 * whichblock and blocks are each dynamically allocated in
183 * their own right, but the subarrays in blocks are appended
184 * to the whichblock array, so shouldn't be freed
187 int *whichblock
, **blocks
;
189 #ifdef STANDALONE_SOLVER
191 * Textual descriptions of each block. For normal Sudoku these
192 * are of the form "(1,3)"; for jigsaw they are "starting at
193 * (5,7)". So the sensible usage in both cases is to say
194 * "elimination within block %s" with one of these strings.
196 * Only blocknames itself needs individually freeing; it's all
205 * For historical reasons, I use `cr' to denote the overall
206 * width/height of the puzzle. It was a natural notation when
207 * all puzzles were divided into blocks in a grid, but doesn't
208 * really make much sense given jigsaw puzzles. However, the
209 * obvious `n' is heavily used in the solver to describe the
210 * index of a number being placed, so `cr' will have to stay.
213 struct block_structure
*blocks
;
216 unsigned char *pencil
; /* c*r*c*r elements */
217 unsigned char *immutable
; /* marks which digits are clues */
218 int completed
, cheated
;
221 static game_params
*default_params(void)
223 game_params
*ret
= snew(game_params
);
227 ret
->symm
= SYMM_ROT2
; /* a plausible default */
228 ret
->diff
= DIFF_BLOCK
; /* so is this */
233 static void free_params(game_params
*params
)
238 static game_params
*dup_params(game_params
*params
)
240 game_params
*ret
= snew(game_params
);
241 *ret
= *params
; /* structure copy */
245 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
251 { "2x2 Trivial", { 2, 2, SYMM_ROT2
, DIFF_BLOCK
, FALSE
} },
252 { "2x3 Basic", { 2, 3, SYMM_ROT2
, DIFF_SIMPLE
, FALSE
} },
253 { "3x3 Trivial", { 3, 3, SYMM_ROT2
, DIFF_BLOCK
, FALSE
} },
254 { "3x3 Basic", { 3, 3, SYMM_ROT2
, DIFF_SIMPLE
, FALSE
} },
255 { "3x3 Basic X", { 3, 3, SYMM_ROT2
, DIFF_SIMPLE
, TRUE
} },
256 { "3x3 Intermediate", { 3, 3, SYMM_ROT2
, DIFF_INTERSECT
, FALSE
} },
257 { "3x3 Advanced", { 3, 3, SYMM_ROT2
, DIFF_SET
, FALSE
} },
258 { "3x3 Advanced X", { 3, 3, SYMM_ROT2
, DIFF_SET
, TRUE
} },
259 { "3x3 Extreme", { 3, 3, SYMM_ROT2
, DIFF_EXTREME
, FALSE
} },
260 { "3x3 Unreasonable", { 3, 3, SYMM_ROT2
, DIFF_RECURSIVE
, FALSE
} },
262 { "3x4 Basic", { 3, 4, SYMM_ROT2
, DIFF_SIMPLE
, FALSE
} },
263 { "4x4 Basic", { 4, 4, SYMM_ROT2
, DIFF_SIMPLE
, FALSE
} },
267 if (i
< 0 || i
>= lenof(presets
))
270 *name
= dupstr(presets
[i
].title
);
271 *params
= dup_params(&presets
[i
].params
);
276 static void decode_params(game_params
*ret
, char const *string
)
280 ret
->c
= ret
->r
= atoi(string
);
282 while (*string
&& isdigit((unsigned char)*string
)) string
++;
283 if (*string
== 'x') {
285 ret
->r
= atoi(string
);
287 while (*string
&& isdigit((unsigned char)*string
)) string
++;
290 if (*string
== 'j') {
295 } else if (*string
== 'x') {
298 } else if (*string
== 'r' || *string
== 'm' || *string
== 'a') {
301 if (sc
== 'm' && *string
== 'd') {
308 while (*string
&& isdigit((unsigned char)*string
)) string
++;
309 if (sc
== 'm' && sn
== 8)
310 ret
->symm
= SYMM_REF8
;
311 if (sc
== 'm' && sn
== 4)
312 ret
->symm
= sd ? SYMM_REF4D
: SYMM_REF4
;
313 if (sc
== 'm' && sn
== 2)
314 ret
->symm
= sd ? SYMM_REF2D
: SYMM_REF2
;
315 if (sc
== 'r' && sn
== 4)
316 ret
->symm
= SYMM_ROT4
;
317 if (sc
== 'r' && sn
== 2)
318 ret
->symm
= SYMM_ROT2
;
320 ret
->symm
= SYMM_NONE
;
321 } else if (*string
== 'd') {
323 if (*string
== 't') /* trivial */
324 string
++, ret
->diff
= DIFF_BLOCK
;
325 else if (*string
== 'b') /* basic */
326 string
++, ret
->diff
= DIFF_SIMPLE
;
327 else if (*string
== 'i') /* intermediate */
328 string
++, ret
->diff
= DIFF_INTERSECT
;
329 else if (*string
== 'a') /* advanced */
330 string
++, ret
->diff
= DIFF_SET
;
331 else if (*string
== 'e') /* extreme */
332 string
++, ret
->diff
= DIFF_EXTREME
;
333 else if (*string
== 'u') /* unreasonable */
334 string
++, ret
->diff
= DIFF_RECURSIVE
;
336 string
++; /* eat unknown character */
340 static char *encode_params(game_params
*params
, int full
)
345 sprintf(str
, "%dx%d", params
->c
, params
->r
);
347 sprintf(str
, "%dj", params
->c
);
352 switch (params
->symm
) {
353 case SYMM_REF8
: strcat(str
, "m8"); break;
354 case SYMM_REF4
: strcat(str
, "m4"); break;
355 case SYMM_REF4D
: strcat(str
, "md4"); break;
356 case SYMM_REF2
: strcat(str
, "m2"); break;
357 case SYMM_REF2D
: strcat(str
, "md2"); break;
358 case SYMM_ROT4
: strcat(str
, "r4"); break;
359 /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
360 case SYMM_NONE
: strcat(str
, "a"); break;
362 switch (params
->diff
) {
363 /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
364 case DIFF_SIMPLE
: strcat(str
, "db"); break;
365 case DIFF_INTERSECT
: strcat(str
, "di"); break;
366 case DIFF_SET
: strcat(str
, "da"); break;
367 case DIFF_EXTREME
: strcat(str
, "de"); break;
368 case DIFF_RECURSIVE
: strcat(str
, "du"); break;
374 static config_item
*game_configure(game_params
*params
)
379 ret
= snewn(6, config_item
);
381 ret
[0].name
= "Columns of sub-blocks";
382 ret
[0].type
= C_STRING
;
383 sprintf(buf
, "%d", params
->c
);
384 ret
[0].sval
= dupstr(buf
);
387 ret
[1].name
= "Rows of sub-blocks";
388 ret
[1].type
= C_STRING
;
389 sprintf(buf
, "%d", params
->r
);
390 ret
[1].sval
= dupstr(buf
);
393 ret
[2].name
= "\"X\" (require every number in each main diagonal)";
394 ret
[2].type
= C_BOOLEAN
;
396 ret
[2].ival
= params
->xtype
;
398 ret
[3].name
= "Symmetry";
399 ret
[3].type
= C_CHOICES
;
400 ret
[3].sval
= ":None:2-way rotation:4-way rotation:2-way mirror:"
401 "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
403 ret
[3].ival
= params
->symm
;
405 ret
[4].name
= "Difficulty";
406 ret
[4].type
= C_CHOICES
;
407 ret
[4].sval
= ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
408 ret
[4].ival
= params
->diff
;
418 static game_params
*custom_params(config_item
*cfg
)
420 game_params
*ret
= snew(game_params
);
422 ret
->c
= atoi(cfg
[0].sval
);
423 ret
->r
= atoi(cfg
[1].sval
);
424 ret
->xtype
= cfg
[2].ival
;
425 ret
->symm
= cfg
[3].ival
;
426 ret
->diff
= cfg
[4].ival
;
431 static char *validate_params(game_params
*params
, int full
)
434 return "Both dimensions must be at least 2";
435 if (params
->c
> ORDER_MAX
|| params
->r
> ORDER_MAX
)
436 return "Dimensions greater than "STR(ORDER_MAX
)" are not supported";
437 if ((params
->c
* params
->r
) > 35)
438 return "Unable to support more than 35 distinct symbols in a puzzle";
442 /* ----------------------------------------------------------------------
445 * This solver is used for two purposes:
446 * + to check solubility of a grid as we gradually remove numbers
448 * + to solve an externally generated puzzle when the user selects
451 * It supports a variety of specific modes of reasoning. By
452 * enabling or disabling subsets of these modes we can arrange a
453 * range of difficulty levels.
457 * Modes of reasoning currently supported:
459 * - Positional elimination: a number must go in a particular
460 * square because all the other empty squares in a given
461 * row/col/blk are ruled out.
463 * - Numeric elimination: a square must have a particular number
464 * in because all the other numbers that could go in it are
467 * - Intersectional analysis: given two domains which overlap
468 * (hence one must be a block, and the other can be a row or
469 * col), if the possible locations for a particular number in
470 * one of the domains can be narrowed down to the overlap, then
471 * that number can be ruled out everywhere but the overlap in
472 * the other domain too.
474 * - Set elimination: if there is a subset of the empty squares
475 * within a domain such that the union of the possible numbers
476 * in that subset has the same size as the subset itself, then
477 * those numbers can be ruled out everywhere else in the domain.
478 * (For example, if there are five empty squares and the
479 * possible numbers in each are 12, 23, 13, 134 and 1345, then
480 * the first three empty squares form such a subset: the numbers
481 * 1, 2 and 3 _must_ be in those three squares in some
482 * permutation, and hence we can deduce none of them can be in
483 * the fourth or fifth squares.)
484 * + You can also see this the other way round, concentrating
485 * on numbers rather than squares: if there is a subset of
486 * the unplaced numbers within a domain such that the union
487 * of all their possible positions has the same size as the
488 * subset itself, then all other numbers can be ruled out for
489 * those positions. However, it turns out that this is
490 * exactly equivalent to the first formulation at all times:
491 * there is a 1-1 correspondence between suitable subsets of
492 * the unplaced numbers and suitable subsets of the unfilled
493 * places, found by taking the _complement_ of the union of
494 * the numbers' possible positions (or the spaces' possible
497 * - Forcing chains (see comment for solver_forcing().)
499 * - Recursion. If all else fails, we pick one of the currently
500 * most constrained empty squares and take a random guess at its
501 * contents, then continue solving on that basis and see if we
505 struct solver_usage
{
507 struct block_structure
*blocks
;
509 * We set up a cubic array, indexed by x, y and digit; each
510 * element of this array is TRUE or FALSE according to whether
511 * or not that digit _could_ in principle go in that position.
513 * The way to index this array is cube[(y*cr+x)*cr+n-1]; there
514 * are macros below to help with this.
518 * This is the grid in which we write down our final
519 * deductions. y-coordinates in here are _not_ transformed.
523 * Now we keep track, at a slightly higher level, of what we
524 * have yet to work out, to prevent doing the same deduction
527 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
529 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
531 /* blk[i*cr+n-1] TRUE if digit n has been placed in block i */
533 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
534 unsigned char *diag
; /* diag 0 is \, 1 is / */
536 #define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
537 #define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
538 #define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
539 #define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
541 #define ondiag0(xy) ((xy) % (cr+1) == 0)
542 #define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
543 #define diag0(i) ((i) * (cr+1))
544 #define diag1(i) ((i+1) * (cr-1))
547 * Function called when we are certain that a particular square has
548 * a particular number in it. The y-coordinate passed in here is
551 static void solver_place(struct solver_usage
*usage
, int x
, int y
, int n
)
554 int sqindex
= y
*cr
+x
;
560 * Rule out all other numbers in this square.
562 for (i
= 1; i
<= cr
; i
++)
567 * Rule out this number in all other positions in the row.
569 for (i
= 0; i
< cr
; i
++)
574 * Rule out this number in all other positions in the column.
576 for (i
= 0; i
< cr
; i
++)
581 * Rule out this number in all other positions in the block.
583 bi
= usage
->blocks
->whichblock
[sqindex
];
584 for (i
= 0; i
< cr
; i
++) {
585 int bp
= usage
->blocks
->blocks
[bi
][i
];
591 * Enter the number in the result grid.
593 usage
->grid
[sqindex
] = n
;
596 * Cross out this number from the list of numbers left to place
597 * in its row, its column and its block.
599 usage
->row
[y
*cr
+n
-1] = usage
->col
[x
*cr
+n
-1] =
600 usage
->blk
[bi
*cr
+n
-1] = TRUE
;
603 if (ondiag0(sqindex
)) {
604 for (i
= 0; i
< cr
; i
++)
605 if (diag0(i
) != sqindex
)
606 cube2(diag0(i
),n
) = FALSE
;
607 usage
->diag
[n
-1] = TRUE
;
609 if (ondiag1(sqindex
)) {
610 for (i
= 0; i
< cr
; i
++)
611 if (diag1(i
) != sqindex
)
612 cube2(diag1(i
),n
) = FALSE
;
613 usage
->diag
[cr
+n
-1] = TRUE
;
618 static int solver_elim(struct solver_usage
*usage
, int *indices
619 #ifdef STANDALONE_SOLVER
628 * Count the number of set bits within this section of the
633 for (i
= 0; i
< cr
; i
++)
634 if (usage
->cube
[indices
[i
]]) {
648 if (!usage
->grid
[y
*cr
+x
]) {
649 #ifdef STANDALONE_SOLVER
650 if (solver_show_working
) {
652 printf("%*s", solver_recurse_depth
*4, "");
656 printf(":\n%*s placing %d at (%d,%d)\n",
657 solver_recurse_depth
*4, "", n
, 1+x
, 1+y
);
660 solver_place(usage
, x
, y
, n
);
664 #ifdef STANDALONE_SOLVER
665 if (solver_show_working
) {
667 printf("%*s", solver_recurse_depth
*4, "");
671 printf(":\n%*s no possibilities available\n",
672 solver_recurse_depth
*4, "");
681 static int solver_intersect(struct solver_usage
*usage
,
682 int *indices1
, int *indices2
683 #ifdef STANDALONE_SOLVER
692 * Loop over the first domain and see if there's any set bit
693 * not also in the second.
695 for (i
= j
= 0; i
< cr
; i
++) {
697 while (j
< cr
&& indices2
[j
] < p
)
699 if (usage
->cube
[p
]) {
700 if (j
< cr
&& indices2
[j
] == p
)
701 continue; /* both domains contain this index */
703 return 0; /* there is, so we can't deduce */
708 * We have determined that all set bits in the first domain are
709 * within its overlap with the second. So loop over the second
710 * domain and remove all set bits that aren't also in that
711 * overlap; return +1 iff we actually _did_ anything.
714 for (i
= j
= 0; i
< cr
; i
++) {
716 while (j
< cr
&& indices1
[j
] < p
)
718 if (usage
->cube
[p
] && (j
>= cr
|| indices1
[j
] != p
)) {
719 #ifdef STANDALONE_SOLVER
720 if (solver_show_working
) {
725 printf("%*s", solver_recurse_depth
*4, "");
737 printf("%*s ruling out %d at (%d,%d)\n",
738 solver_recurse_depth
*4, "", pn
, 1+px
, 1+py
);
741 ret
= +1; /* we did something */
749 struct solver_scratch
{
750 unsigned char *grid
, *rowidx
, *colidx
, *set
;
751 int *neighbours
, *bfsqueue
;
752 int *indexlist
, *indexlist2
;
753 #ifdef STANDALONE_SOLVER
758 static int solver_set(struct solver_usage
*usage
,
759 struct solver_scratch
*scratch
,
761 #ifdef STANDALONE_SOLVER
768 unsigned char *grid
= scratch
->grid
;
769 unsigned char *rowidx
= scratch
->rowidx
;
770 unsigned char *colidx
= scratch
->colidx
;
771 unsigned char *set
= scratch
->set
;
774 * We are passed a cr-by-cr matrix of booleans. Our first job
775 * is to winnow it by finding any definite placements - i.e.
776 * any row with a solitary 1 - and discarding that row and the
777 * column containing the 1.
779 memset(rowidx
, TRUE
, cr
);
780 memset(colidx
, TRUE
, cr
);
781 for (i
= 0; i
< cr
; i
++) {
782 int count
= 0, first
= -1;
783 for (j
= 0; j
< cr
; j
++)
784 if (usage
->cube
[indices
[i
*cr
+j
]])
788 * If count == 0, then there's a row with no 1s at all and
789 * the puzzle is internally inconsistent. However, we ought
790 * to have caught this already during the simpler reasoning
791 * methods, so we can safely fail an assertion if we reach
796 rowidx
[i
] = colidx
[first
] = FALSE
;
800 * Convert each of rowidx/colidx from a list of 0s and 1s to a
801 * list of the indices of the 1s.
803 for (i
= j
= 0; i
< cr
; i
++)
807 for (i
= j
= 0; i
< cr
; i
++)
813 * And create the smaller matrix.
815 for (i
= 0; i
< n
; i
++)
816 for (j
= 0; j
< n
; j
++)
817 grid
[i
*cr
+j
] = usage
->cube
[indices
[rowidx
[i
]*cr
+colidx
[j
]]];
820 * Having done that, we now have a matrix in which every row
821 * has at least two 1s in. Now we search to see if we can find
822 * a rectangle of zeroes (in the set-theoretic sense of
823 * `rectangle', i.e. a subset of rows crossed with a subset of
824 * columns) whose width and height add up to n.
831 * We have a candidate set. If its size is <=1 or >=n-1
832 * then we move on immediately.
834 if (count
> 1 && count
< n
-1) {
836 * The number of rows we need is n-count. See if we can
837 * find that many rows which each have a zero in all
838 * the positions listed in `set'.
841 for (i
= 0; i
< n
; i
++) {
843 for (j
= 0; j
< n
; j
++)
844 if (set
[j
] && grid
[i
*cr
+j
]) {
853 * We expect never to be able to get _more_ than
854 * n-count suitable rows: this would imply that (for
855 * example) there are four numbers which between them
856 * have at most three possible positions, and hence it
857 * indicates a faulty deduction before this point or
860 if (rows
> n
- count
) {
861 #ifdef STANDALONE_SOLVER
862 if (solver_show_working
) {
864 printf("%*s", solver_recurse_depth
*4,
869 printf(":\n%*s contradiction reached\n",
870 solver_recurse_depth
*4, "");
876 if (rows
>= n
- count
) {
877 int progress
= FALSE
;
880 * We've got one! Now, for each row which _doesn't_
881 * satisfy the criterion, eliminate all its set
882 * bits in the positions _not_ listed in `set'.
883 * Return +1 (meaning progress has been made) if we
884 * successfully eliminated anything at all.
886 * This involves referring back through
887 * rowidx/colidx in order to work out which actual
888 * positions in the cube to meddle with.
890 for (i
= 0; i
< n
; i
++) {
892 for (j
= 0; j
< n
; j
++)
893 if (set
[j
] && grid
[i
*cr
+j
]) {
898 for (j
= 0; j
< n
; j
++)
899 if (!set
[j
] && grid
[i
*cr
+j
]) {
900 int fpos
= indices
[rowidx
[i
]*cr
+colidx
[j
]];
901 #ifdef STANDALONE_SOLVER
902 if (solver_show_working
) {
907 printf("%*s", solver_recurse_depth
*4,
920 printf("%*s ruling out %d at (%d,%d)\n",
921 solver_recurse_depth
*4, "",
926 usage
->cube
[fpos
] = FALSE
;
938 * Binary increment: change the rightmost 0 to a 1, and
939 * change all 1s to the right of it to 0s.
942 while (i
> 0 && set
[i
-1])
943 set
[--i
] = 0, count
--;
945 set
[--i
] = 1, count
++;
954 * Look for forcing chains. A forcing chain is a path of
955 * pairwise-exclusive squares (i.e. each pair of adjacent squares
956 * in the path are in the same row, column or block) with the
957 * following properties:
959 * (a) Each square on the path has precisely two possible numbers.
961 * (b) Each pair of squares which are adjacent on the path share
962 * at least one possible number in common.
964 * (c) Each square in the middle of the path shares _both_ of its
965 * numbers with at least one of its neighbours (not the same
966 * one with both neighbours).
968 * These together imply that at least one of the possible number
969 * choices at one end of the path forces _all_ the rest of the
970 * numbers along the path. In order to make real use of this, we
971 * need further properties:
973 * (c) Ruling out some number N from the square at one end of the
974 * path forces the square at the other end to take the same
977 * (d) The two end squares are both in line with some third
980 * (e) That third square currently has N as a possibility.
982 * If we can find all of that lot, we can deduce that at least one
983 * of the two ends of the forcing chain has number N, and that
984 * therefore the mutually adjacent third square does not.
986 * To find forcing chains, we're going to start a bfs at each
987 * suitable square, once for each of its two possible numbers.
989 static int solver_forcing(struct solver_usage
*usage
,
990 struct solver_scratch
*scratch
)
993 int *bfsqueue
= scratch
->bfsqueue
;
994 #ifdef STANDALONE_SOLVER
995 int *bfsprev
= scratch
->bfsprev
;
997 unsigned char *number
= scratch
->grid
;
998 int *neighbours
= scratch
->neighbours
;
1001 for (y
= 0; y
< cr
; y
++)
1002 for (x
= 0; x
< cr
; x
++) {
1006 * If this square doesn't have exactly two candidate
1007 * numbers, don't try it.
1009 * In this loop we also sum the candidate numbers,
1010 * which is a nasty hack to allow us to quickly find
1011 * `the other one' (since we will shortly know there
1014 for (count
= t
= 0, n
= 1; n
<= cr
; n
++)
1021 * Now attempt a bfs for each candidate.
1023 for (n
= 1; n
<= cr
; n
++)
1024 if (cube(x
, y
, n
)) {
1025 int orign
, currn
, head
, tail
;
1032 memset(number
, cr
+1, cr
*cr
);
1034 bfsqueue
[tail
++] = y
*cr
+x
;
1035 #ifdef STANDALONE_SOLVER
1036 bfsprev
[y
*cr
+x
] = -1;
1038 number
[y
*cr
+x
] = t
- n
;
1040 while (head
< tail
) {
1041 int xx
, yy
, nneighbours
, xt
, yt
, i
;
1043 xx
= bfsqueue
[head
++];
1047 currn
= number
[yy
*cr
+xx
];
1050 * Find neighbours of yy,xx.
1053 for (yt
= 0; yt
< cr
; yt
++)
1054 neighbours
[nneighbours
++] = yt
*cr
+xx
;
1055 for (xt
= 0; xt
< cr
; xt
++)
1056 neighbours
[nneighbours
++] = yy
*cr
+xt
;
1057 xt
= usage
->blocks
->whichblock
[yy
*cr
+xx
];
1058 for (yt
= 0; yt
< cr
; yt
++)
1059 neighbours
[nneighbours
++] = usage
->blocks
->blocks
[xt
][yt
];
1061 int sqindex
= yy
*cr
+xx
;
1062 if (ondiag0(sqindex
)) {
1063 for (i
= 0; i
< cr
; i
++)
1064 neighbours
[nneighbours
++] = diag0(i
);
1066 if (ondiag1(sqindex
)) {
1067 for (i
= 0; i
< cr
; i
++)
1068 neighbours
[nneighbours
++] = diag1(i
);
1073 * Try visiting each of those neighbours.
1075 for (i
= 0; i
< nneighbours
; i
++) {
1078 xt
= neighbours
[i
] % cr
;
1079 yt
= neighbours
[i
] / cr
;
1082 * We need this square to not be
1083 * already visited, and to include
1084 * currn as a possible number.
1086 if (number
[yt
*cr
+xt
] <= cr
)
1088 if (!cube(xt
, yt
, currn
))
1092 * Don't visit _this_ square a second
1095 if (xt
== xx
&& yt
== yy
)
1099 * To continue with the bfs, we need
1100 * this square to have exactly two
1103 for (cc
= tt
= 0, nn
= 1; nn
<= cr
; nn
++)
1104 if (cube(xt
, yt
, nn
))
1107 bfsqueue
[tail
++] = yt
*cr
+xt
;
1108 #ifdef STANDALONE_SOLVER
1109 bfsprev
[yt
*cr
+xt
] = yy
*cr
+xx
;
1111 number
[yt
*cr
+xt
] = tt
- currn
;
1115 * One other possibility is that this
1116 * might be the square in which we can
1117 * make a real deduction: if it's
1118 * adjacent to x,y, and currn is equal
1119 * to the original number we ruled out.
1121 if (currn
== orign
&&
1122 (xt
== x
|| yt
== y
||
1123 (usage
->blocks
->whichblock
[yt
*cr
+xt
] == usage
->blocks
->whichblock
[y
*cr
+x
]) ||
1124 (usage
->diag
&& ((ondiag0(yt
*cr
+xt
) && ondiag0(y
*cr
+x
)) ||
1125 (ondiag1(yt
*cr
+xt
) && ondiag1(y
*cr
+x
)))))) {
1126 #ifdef STANDALONE_SOLVER
1127 if (solver_show_working
) {
1130 printf("%*sforcing chain, %d at ends of ",
1131 solver_recurse_depth
*4, "", orign
);
1135 printf("%s(%d,%d)", sep
, 1+xl
,
1137 xl
= bfsprev
[yl
*cr
+xl
];
1144 printf("\n%*s ruling out %d at (%d,%d)\n",
1145 solver_recurse_depth
*4, "",
1149 cube(xt
, yt
, orign
) = FALSE
;
1160 static struct solver_scratch
*solver_new_scratch(struct solver_usage
*usage
)
1162 struct solver_scratch
*scratch
= snew(struct solver_scratch
);
1164 scratch
->grid
= snewn(cr
*cr
, unsigned char);
1165 scratch
->rowidx
= snewn(cr
, unsigned char);
1166 scratch
->colidx
= snewn(cr
, unsigned char);
1167 scratch
->set
= snewn(cr
, unsigned char);
1168 scratch
->neighbours
= snewn(5*cr
, int);
1169 scratch
->bfsqueue
= snewn(cr
*cr
, int);
1170 #ifdef STANDALONE_SOLVER
1171 scratch
->bfsprev
= snewn(cr
*cr
, int);
1173 scratch
->indexlist
= snewn(cr
*cr
, int); /* used for set elimination */
1174 scratch
->indexlist2
= snewn(cr
, int); /* only used for intersect() */
1178 static void solver_free_scratch(struct solver_scratch
*scratch
)
1180 #ifdef STANDALONE_SOLVER
1181 sfree(scratch
->bfsprev
);
1183 sfree(scratch
->bfsqueue
);
1184 sfree(scratch
->neighbours
);
1185 sfree(scratch
->set
);
1186 sfree(scratch
->colidx
);
1187 sfree(scratch
->rowidx
);
1188 sfree(scratch
->grid
);
1189 sfree(scratch
->indexlist
);
1190 sfree(scratch
->indexlist2
);
1194 static int solver(int cr
, struct block_structure
*blocks
, int xtype
,
1195 digit
*grid
, int maxdiff
)
1197 struct solver_usage
*usage
;
1198 struct solver_scratch
*scratch
;
1199 int x
, y
, b
, i
, n
, ret
;
1200 int diff
= DIFF_BLOCK
;
1203 * Set up a usage structure as a clean slate (everything
1206 usage
= snew(struct solver_usage
);
1208 usage
->blocks
= blocks
;
1209 usage
->cube
= snewn(cr
*cr
*cr
, unsigned char);
1210 usage
->grid
= grid
; /* write straight back to the input */
1211 memset(usage
->cube
, TRUE
, cr
*cr
*cr
);
1213 usage
->row
= snewn(cr
* cr
, unsigned char);
1214 usage
->col
= snewn(cr
* cr
, unsigned char);
1215 usage
->blk
= snewn(cr
* cr
, unsigned char);
1216 memset(usage
->row
, FALSE
, cr
* cr
);
1217 memset(usage
->col
, FALSE
, cr
* cr
);
1218 memset(usage
->blk
, FALSE
, cr
* cr
);
1221 usage
->diag
= snewn(cr
* 2, unsigned char);
1222 memset(usage
->diag
, FALSE
, cr
* 2);
1226 scratch
= solver_new_scratch(usage
);
1229 * Place all the clue numbers we are given.
1231 for (x
= 0; x
< cr
; x
++)
1232 for (y
= 0; y
< cr
; y
++)
1234 solver_place(usage
, x
, y
, grid
[y
*cr
+x
]);
1237 * Now loop over the grid repeatedly trying all permitted modes
1238 * of reasoning. The loop terminates if we complete an
1239 * iteration without making any progress; we then return
1240 * failure or success depending on whether the grid is full or
1245 * I'd like to write `continue;' inside each of the
1246 * following loops, so that the solver returns here after
1247 * making some progress. However, I can't specify that I
1248 * want to continue an outer loop rather than the innermost
1249 * one, so I'm apologetically resorting to a goto.
1254 * Blockwise positional elimination.
1256 for (b
= 0; b
< cr
; b
++)
1257 for (n
= 1; n
<= cr
; n
++)
1258 if (!usage
->blk
[b
*cr
+n
-1]) {
1259 for (i
= 0; i
< cr
; i
++)
1260 scratch
->indexlist
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
],n
);
1261 ret
= solver_elim(usage
, scratch
->indexlist
1262 #ifdef STANDALONE_SOLVER
1263 , "positional elimination,"
1264 " %d in block %s", n
,
1265 usage
->blocks
->blocknames
[b
]
1269 diff
= DIFF_IMPOSSIBLE
;
1271 } else if (ret
> 0) {
1272 diff
= max(diff
, DIFF_BLOCK
);
1277 if (maxdiff
<= DIFF_BLOCK
)
1281 * Row-wise positional elimination.
1283 for (y
= 0; y
< cr
; y
++)
1284 for (n
= 1; n
<= cr
; n
++)
1285 if (!usage
->row
[y
*cr
+n
-1]) {
1286 for (x
= 0; x
< cr
; x
++)
1287 scratch
->indexlist
[x
] = cubepos(x
, y
, n
);
1288 ret
= solver_elim(usage
, scratch
->indexlist
1289 #ifdef STANDALONE_SOLVER
1290 , "positional elimination,"
1291 " %d in row %d", n
, 1+y
1295 diff
= DIFF_IMPOSSIBLE
;
1297 } else if (ret
> 0) {
1298 diff
= max(diff
, DIFF_SIMPLE
);
1303 * Column-wise positional elimination.
1305 for (x
= 0; x
< cr
; x
++)
1306 for (n
= 1; n
<= cr
; n
++)
1307 if (!usage
->col
[x
*cr
+n
-1]) {
1308 for (y
= 0; y
< cr
; y
++)
1309 scratch
->indexlist
[y
] = cubepos(x
, y
, n
);
1310 ret
= solver_elim(usage
, scratch
->indexlist
1311 #ifdef STANDALONE_SOLVER
1312 , "positional elimination,"
1313 " %d in column %d", n
, 1+x
1317 diff
= DIFF_IMPOSSIBLE
;
1319 } else if (ret
> 0) {
1320 diff
= max(diff
, DIFF_SIMPLE
);
1326 * X-diagonal positional elimination.
1329 for (n
= 1; n
<= cr
; n
++)
1330 if (!usage
->diag
[n
-1]) {
1331 for (i
= 0; i
< cr
; i
++)
1332 scratch
->indexlist
[i
] = cubepos2(diag0(i
), n
);
1333 ret
= solver_elim(usage
, scratch
->indexlist
1334 #ifdef STANDALONE_SOLVER
1335 , "positional elimination,"
1336 " %d in \\-diagonal", n
1340 diff
= DIFF_IMPOSSIBLE
;
1342 } else if (ret
> 0) {
1343 diff
= max(diff
, DIFF_SIMPLE
);
1347 for (n
= 1; n
<= cr
; n
++)
1348 if (!usage
->diag
[cr
+n
-1]) {
1349 for (i
= 0; i
< cr
; i
++)
1350 scratch
->indexlist
[i
] = cubepos2(diag1(i
), n
);
1351 ret
= solver_elim(usage
, scratch
->indexlist
1352 #ifdef STANDALONE_SOLVER
1353 , "positional elimination,"
1354 " %d in /-diagonal", n
1358 diff
= DIFF_IMPOSSIBLE
;
1360 } else if (ret
> 0) {
1361 diff
= max(diff
, DIFF_SIMPLE
);
1368 * Numeric elimination.
1370 for (x
= 0; x
< cr
; x
++)
1371 for (y
= 0; y
< cr
; y
++)
1372 if (!usage
->grid
[y
*cr
+x
]) {
1373 for (n
= 1; n
<= cr
; n
++)
1374 scratch
->indexlist
[n
-1] = cubepos(x
, y
, n
);
1375 ret
= solver_elim(usage
, scratch
->indexlist
1376 #ifdef STANDALONE_SOLVER
1377 , "numeric elimination at (%d,%d)",
1382 diff
= DIFF_IMPOSSIBLE
;
1384 } else if (ret
> 0) {
1385 diff
= max(diff
, DIFF_SIMPLE
);
1390 if (maxdiff
<= DIFF_SIMPLE
)
1394 * Intersectional analysis, rows vs blocks.
1396 for (y
= 0; y
< cr
; y
++)
1397 for (b
= 0; b
< cr
; b
++)
1398 for (n
= 1; n
<= cr
; n
++) {
1399 if (usage
->row
[y
*cr
+n
-1] ||
1400 usage
->blk
[b
*cr
+n
-1])
1402 for (i
= 0; i
< cr
; i
++) {
1403 scratch
->indexlist
[i
] = cubepos(i
, y
, n
);
1404 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
1407 * solver_intersect() never returns -1.
1409 if (solver_intersect(usage
, scratch
->indexlist
,
1411 #ifdef STANDALONE_SOLVER
1412 , "intersectional analysis,"
1413 " %d in row %d vs block %s",
1414 n
, 1+y
, usage
->blocks
->blocknames
[b
]
1417 solver_intersect(usage
, scratch
->indexlist2
,
1419 #ifdef STANDALONE_SOLVER
1420 , "intersectional analysis,"
1421 " %d in block %s vs row %d",
1422 n
, usage
->blocks
->blocknames
[b
], 1+y
1425 diff
= max(diff
, DIFF_INTERSECT
);
1431 * Intersectional analysis, columns vs blocks.
1433 for (x
= 0; x
< cr
; x
++)
1434 for (b
= 0; b
< cr
; b
++)
1435 for (n
= 1; n
<= cr
; n
++) {
1436 if (usage
->col
[x
*cr
+n
-1] ||
1437 usage
->blk
[b
*cr
+n
-1])
1439 for (i
= 0; i
< cr
; i
++) {
1440 scratch
->indexlist
[i
] = cubepos(x
, i
, n
);
1441 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
1443 if (solver_intersect(usage
, scratch
->indexlist
,
1445 #ifdef STANDALONE_SOLVER
1446 , "intersectional analysis,"
1447 " %d in column %d vs block %s",
1448 n
, 1+x
, usage
->blocks
->blocknames
[b
]
1451 solver_intersect(usage
, scratch
->indexlist2
,
1453 #ifdef STANDALONE_SOLVER
1454 , "intersectional analysis,"
1455 " %d in block %s vs column %d",
1456 n
, usage
->blocks
->blocknames
[b
], 1+x
1459 diff
= max(diff
, DIFF_INTERSECT
);
1466 * Intersectional analysis, \-diagonal vs blocks.
1468 for (b
= 0; b
< cr
; b
++)
1469 for (n
= 1; n
<= cr
; n
++) {
1470 if (usage
->diag
[n
-1] ||
1471 usage
->blk
[b
*cr
+n
-1])
1473 for (i
= 0; i
< cr
; i
++) {
1474 scratch
->indexlist
[i
] = cubepos2(diag0(i
), n
);
1475 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
1477 if (solver_intersect(usage
, scratch
->indexlist
,
1479 #ifdef STANDALONE_SOLVER
1480 , "intersectional analysis,"
1481 " %d in \\-diagonal vs block %s",
1482 n
, 1+x
, usage
->blocks
->blocknames
[b
]
1485 solver_intersect(usage
, scratch
->indexlist2
,
1487 #ifdef STANDALONE_SOLVER
1488 , "intersectional analysis,"
1489 " %d in block %s vs \\-diagonal",
1490 n
, usage
->blocks
->blocknames
[b
], 1+x
1493 diff
= max(diff
, DIFF_INTERSECT
);
1499 * Intersectional analysis, /-diagonal vs blocks.
1501 for (b
= 0; b
< cr
; b
++)
1502 for (n
= 1; n
<= cr
; n
++) {
1503 if (usage
->diag
[cr
+n
-1] ||
1504 usage
->blk
[b
*cr
+n
-1])
1506 for (i
= 0; i
< cr
; i
++) {
1507 scratch
->indexlist
[i
] = cubepos2(diag1(i
), n
);
1508 scratch
->indexlist2
[i
] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
1510 if (solver_intersect(usage
, scratch
->indexlist
,
1512 #ifdef STANDALONE_SOLVER
1513 , "intersectional analysis,"
1514 " %d in /-diagonal vs block %s",
1515 n
, 1+x
, usage
->blocks
->blocknames
[b
]
1518 solver_intersect(usage
, scratch
->indexlist2
,
1520 #ifdef STANDALONE_SOLVER
1521 , "intersectional analysis,"
1522 " %d in block %s vs /-diagonal",
1523 n
, usage
->blocks
->blocknames
[b
], 1+x
1526 diff
= max(diff
, DIFF_INTERSECT
);
1532 if (maxdiff
<= DIFF_INTERSECT
)
1536 * Blockwise set elimination.
1538 for (b
= 0; b
< cr
; b
++) {
1539 for (i
= 0; i
< cr
; i
++)
1540 for (n
= 1; n
<= cr
; n
++)
1541 scratch
->indexlist
[i
*cr
+n
-1] = cubepos2(usage
->blocks
->blocks
[b
][i
], n
);
1542 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1543 #ifdef STANDALONE_SOLVER
1544 , "set elimination, block %s",
1545 usage
->blocks
->blocknames
[b
]
1549 diff
= DIFF_IMPOSSIBLE
;
1551 } else if (ret
> 0) {
1552 diff
= max(diff
, DIFF_SET
);
1558 * Row-wise set elimination.
1560 for (y
= 0; y
< cr
; y
++) {
1561 for (x
= 0; x
< cr
; x
++)
1562 for (n
= 1; n
<= cr
; n
++)
1563 scratch
->indexlist
[x
*cr
+n
-1] = cubepos(x
, y
, n
);
1564 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1565 #ifdef STANDALONE_SOLVER
1566 , "set elimination, row %d", 1+y
1570 diff
= DIFF_IMPOSSIBLE
;
1572 } else if (ret
> 0) {
1573 diff
= max(diff
, DIFF_SET
);
1579 * Column-wise set elimination.
1581 for (x
= 0; x
< cr
; x
++) {
1582 for (y
= 0; y
< cr
; y
++)
1583 for (n
= 1; n
<= cr
; n
++)
1584 scratch
->indexlist
[y
*cr
+n
-1] = cubepos(x
, y
, n
);
1585 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1586 #ifdef STANDALONE_SOLVER
1587 , "set elimination, column %d", 1+x
1591 diff
= DIFF_IMPOSSIBLE
;
1593 } else if (ret
> 0) {
1594 diff
= max(diff
, DIFF_SET
);
1601 * \-diagonal set elimination.
1603 for (i
= 0; i
< cr
; i
++)
1604 for (n
= 1; n
<= cr
; n
++)
1605 scratch
->indexlist
[i
*cr
+n
-1] = cubepos2(diag0(i
), n
);
1606 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1607 #ifdef STANDALONE_SOLVER
1608 , "set elimination, \\-diagonal"
1612 diff
= DIFF_IMPOSSIBLE
;
1614 } else if (ret
> 0) {
1615 diff
= max(diff
, DIFF_SET
);
1620 * /-diagonal set elimination.
1622 for (i
= 0; i
< cr
; i
++)
1623 for (n
= 1; n
<= cr
; n
++)
1624 scratch
->indexlist
[i
*cr
+n
-1] = cubepos2(diag1(i
), n
);
1625 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1626 #ifdef STANDALONE_SOLVER
1627 , "set elimination, \\-diagonal"
1631 diff
= DIFF_IMPOSSIBLE
;
1633 } else if (ret
> 0) {
1634 diff
= max(diff
, DIFF_SET
);
1639 if (maxdiff
<= DIFF_SET
)
1643 * Row-vs-column set elimination on a single number.
1645 for (n
= 1; n
<= cr
; n
++) {
1646 for (y
= 0; y
< cr
; y
++)
1647 for (x
= 0; x
< cr
; x
++)
1648 scratch
->indexlist
[y
*cr
+x
] = cubepos(x
, y
, n
);
1649 ret
= solver_set(usage
, scratch
, scratch
->indexlist
1650 #ifdef STANDALONE_SOLVER
1651 , "positional set elimination, number %d", n
1655 diff
= DIFF_IMPOSSIBLE
;
1657 } else if (ret
> 0) {
1658 diff
= max(diff
, DIFF_EXTREME
);
1666 if (solver_forcing(usage
, scratch
)) {
1667 diff
= max(diff
, DIFF_EXTREME
);
1672 * If we reach here, we have made no deductions in this
1673 * iteration, so the algorithm terminates.
1679 * Last chance: if we haven't fully solved the puzzle yet, try
1680 * recursing based on guesses for a particular square. We pick
1681 * one of the most constrained empty squares we can find, which
1682 * has the effect of pruning the search tree as much as
1685 if (maxdiff
>= DIFF_RECURSIVE
) {
1686 int best
, bestcount
;
1691 for (y
= 0; y
< cr
; y
++)
1692 for (x
= 0; x
< cr
; x
++)
1693 if (!grid
[y
*cr
+x
]) {
1697 * An unfilled square. Count the number of
1698 * possible digits in it.
1701 for (n
= 1; n
<= cr
; n
++)
1706 * We should have found any impossibilities
1707 * already, so this can safely be an assert.
1711 if (count
< bestcount
) {
1719 digit
*list
, *ingrid
, *outgrid
;
1721 diff
= DIFF_IMPOSSIBLE
; /* no solution found yet */
1724 * Attempt recursion.
1729 list
= snewn(cr
, digit
);
1730 ingrid
= snewn(cr
* cr
, digit
);
1731 outgrid
= snewn(cr
* cr
, digit
);
1732 memcpy(ingrid
, grid
, cr
* cr
);
1734 /* Make a list of the possible digits. */
1735 for (j
= 0, n
= 1; n
<= cr
; n
++)
1739 #ifdef STANDALONE_SOLVER
1740 if (solver_show_working
) {
1742 printf("%*srecursing on (%d,%d) [",
1743 solver_recurse_depth
*4, "", x
+ 1, y
+ 1);
1744 for (i
= 0; i
< j
; i
++) {
1745 printf("%s%d", sep
, list
[i
]);
1753 * And step along the list, recursing back into the
1754 * main solver at every stage.
1756 for (i
= 0; i
< j
; i
++) {
1759 memcpy(outgrid
, ingrid
, cr
* cr
);
1760 outgrid
[y
*cr
+x
] = list
[i
];
1762 #ifdef STANDALONE_SOLVER
1763 if (solver_show_working
)
1764 printf("%*sguessing %d at (%d,%d)\n",
1765 solver_recurse_depth
*4, "", list
[i
], x
+ 1, y
+ 1);
1766 solver_recurse_depth
++;
1769 ret
= solver(cr
, blocks
, xtype
, outgrid
, maxdiff
);
1771 #ifdef STANDALONE_SOLVER
1772 solver_recurse_depth
--;
1773 if (solver_show_working
) {
1774 printf("%*sretracting %d at (%d,%d)\n",
1775 solver_recurse_depth
*4, "", list
[i
], x
+ 1, y
+ 1);
1780 * If we have our first solution, copy it into the
1781 * grid we will return.
1783 if (diff
== DIFF_IMPOSSIBLE
&& ret
!= DIFF_IMPOSSIBLE
)
1784 memcpy(grid
, outgrid
, cr
*cr
);
1786 if (ret
== DIFF_AMBIGUOUS
)
1787 diff
= DIFF_AMBIGUOUS
;
1788 else if (ret
== DIFF_IMPOSSIBLE
)
1789 /* do not change our return value */;
1791 /* the recursion turned up exactly one solution */
1792 if (diff
== DIFF_IMPOSSIBLE
)
1793 diff
= DIFF_RECURSIVE
;
1795 diff
= DIFF_AMBIGUOUS
;
1799 * As soon as we've found more than one solution,
1800 * give up immediately.
1802 if (diff
== DIFF_AMBIGUOUS
)
1813 * We're forbidden to use recursion, so we just see whether
1814 * our grid is fully solved, and return DIFF_IMPOSSIBLE
1817 for (y
= 0; y
< cr
; y
++)
1818 for (x
= 0; x
< cr
; x
++)
1820 diff
= DIFF_IMPOSSIBLE
;
1825 #ifdef STANDALONE_SOLVER
1826 if (solver_show_working
)
1827 printf("%*s%s found\n",
1828 solver_recurse_depth
*4, "",
1829 diff
== DIFF_IMPOSSIBLE ?
"no solution" :
1830 diff
== DIFF_AMBIGUOUS ?
"multiple solutions" :
1840 solver_free_scratch(scratch
);
1845 /* ----------------------------------------------------------------------
1846 * End of solver code.
1849 /* ----------------------------------------------------------------------
1850 * Solo filled-grid generator.
1852 * This grid generator works by essentially trying to solve a grid
1853 * starting from no clues, and not worrying that there's more than
1854 * one possible solution. Unfortunately, it isn't computationally
1855 * feasible to do this by calling the above solver with an empty
1856 * grid, because that one needs to allocate a lot of scratch space
1857 * at every recursion level. Instead, I have a much simpler
1858 * algorithm which I shamelessly copied from a Python solver
1859 * written by Andrew Wilkinson (which is GPLed, but I've reused
1860 * only ideas and no code). It mostly just does the obvious
1861 * recursive thing: pick an empty square, put one of the possible
1862 * digits in it, recurse until all squares are filled, backtrack
1863 * and change some choices if necessary.
1865 * The clever bit is that every time it chooses which square to
1866 * fill in next, it does so by counting the number of _possible_
1867 * numbers that can go in each square, and it prioritises so that
1868 * it picks a square with the _lowest_ number of possibilities. The
1869 * idea is that filling in lots of the obvious bits (particularly
1870 * any squares with only one possibility) will cut down on the list
1871 * of possibilities for other squares and hence reduce the enormous
1872 * search space as much as possible as early as possible.
1876 * Internal data structure used in gridgen to keep track of
1879 struct gridgen_coord
{ int x
, y
, r
; };
1880 struct gridgen_usage
{
1882 struct block_structure
*blocks
;
1883 /* grid is a copy of the input grid, modified as we go along */
1885 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
1887 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
1889 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
1891 /* diag[i*cr+n-1] TRUE if digit n has been placed in diagonal i */
1892 unsigned char *diag
;
1893 /* This lists all the empty spaces remaining in the grid. */
1894 struct gridgen_coord
*spaces
;
1896 /* If we need randomisation in the solve, this is our random state. */
1900 static void gridgen_place(struct gridgen_usage
*usage
, int x
, int y
, digit n
,
1904 usage
->row
[y
*cr
+n
-1] = usage
->col
[x
*cr
+n
-1] =
1905 usage
->blk
[usage
->blocks
->whichblock
[y
*cr
+x
]*cr
+n
-1] = placing
;
1907 if (ondiag0(y
*cr
+x
))
1908 usage
->diag
[n
-1] = placing
;
1909 if (ondiag1(y
*cr
+x
))
1910 usage
->diag
[cr
+n
-1] = placing
;
1912 usage
->grid
[y
*cr
+x
] = placing ? n
: 0;
1916 * The real recursive step in the generating function.
1918 * Return values: 1 means solution found, 0 means no solution
1919 * found on this branch.
1921 static int gridgen_real(struct gridgen_usage
*usage
, digit
*grid
, int *steps
)
1924 int i
, j
, n
, sx
, sy
, bestm
, bestr
, ret
;
1928 * Firstly, check for completion! If there are no spaces left
1929 * in the grid, we have a solution.
1931 if (usage
->nspaces
== 0)
1935 * Next, abandon generation if we went over our steps limit.
1942 * Otherwise, there must be at least one space. Find the most
1943 * constrained space, using the `r' field as a tie-breaker.
1945 bestm
= cr
+1; /* so that any space will beat it */
1948 for (j
= 0; j
< usage
->nspaces
; j
++) {
1949 int x
= usage
->spaces
[j
].x
, y
= usage
->spaces
[j
].y
;
1953 * Find the number of digits that could go in this space.
1956 for (n
= 0; n
< cr
; n
++)
1957 if (!usage
->row
[y
*cr
+n
] && !usage
->col
[x
*cr
+n
] &&
1958 !usage
->blk
[usage
->blocks
->whichblock
[y
*cr
+x
]*cr
+n
] &&
1959 (!usage
->diag
|| ((!ondiag0(y
*cr
+x
) || !usage
->diag
[n
]) &&
1960 (!ondiag1(y
*cr
+x
) || !usage
->diag
[cr
+n
]))))
1963 if (m
< bestm
|| (m
== bestm
&& usage
->spaces
[j
].r
< bestr
)) {
1965 bestr
= usage
->spaces
[j
].r
;
1973 * Swap that square into the final place in the spaces array,
1974 * so that decrementing nspaces will remove it from the list.
1976 if (i
!= usage
->nspaces
-1) {
1977 struct gridgen_coord t
;
1978 t
= usage
->spaces
[usage
->nspaces
-1];
1979 usage
->spaces
[usage
->nspaces
-1] = usage
->spaces
[i
];
1980 usage
->spaces
[i
] = t
;
1984 * Now we've decided which square to start our recursion at,
1985 * simply go through all possible values, shuffling them
1986 * randomly first if necessary.
1988 digits
= snewn(bestm
, int);
1990 for (n
= 0; n
< cr
; n
++)
1991 if (!usage
->row
[sy
*cr
+n
] && !usage
->col
[sx
*cr
+n
] &&
1992 !usage
->blk
[usage
->blocks
->whichblock
[sy
*cr
+sx
]*cr
+n
] &&
1993 (!usage
->diag
|| ((!ondiag0(sy
*cr
+sx
) || !usage
->diag
[n
]) &&
1994 (!ondiag1(sy
*cr
+sx
) || !usage
->diag
[cr
+n
])))) {
1999 shuffle(digits
, j
, sizeof(*digits
), usage
->rs
);
2001 /* And finally, go through the digit list and actually recurse. */
2003 for (i
= 0; i
< j
; i
++) {
2006 /* Update the usage structure to reflect the placing of this digit. */
2007 gridgen_place(usage
, sx
, sy
, n
, TRUE
);
2010 /* Call the solver recursively. Stop when we find a solution. */
2011 if (gridgen_real(usage
, grid
, steps
)) {
2016 /* Revert the usage structure. */
2017 gridgen_place(usage
, sx
, sy
, n
, FALSE
);
2026 * Entry point to generator. You give it parameters and a starting
2027 * grid, which is simply an array of cr*cr digits.
2029 static int gridgen(int cr
, struct block_structure
*blocks
, int xtype
,
2030 digit
*grid
, random_state
*rs
, int maxsteps
)
2032 struct gridgen_usage
*usage
;
2036 * Clear the grid to start with.
2038 memset(grid
, 0, cr
*cr
);
2041 * Create a gridgen_usage structure.
2043 usage
= snew(struct gridgen_usage
);
2046 usage
->blocks
= blocks
;
2050 usage
->row
= snewn(cr
* cr
, unsigned char);
2051 usage
->col
= snewn(cr
* cr
, unsigned char);
2052 usage
->blk
= snewn(cr
* cr
, unsigned char);
2053 memset(usage
->row
, FALSE
, cr
* cr
);
2054 memset(usage
->col
, FALSE
, cr
* cr
);
2055 memset(usage
->blk
, FALSE
, cr
* cr
);
2058 usage
->diag
= snewn(2 * cr
, unsigned char);
2059 memset(usage
->diag
, FALSE
, 2 * cr
);
2065 * Begin by filling in the whole top row with randomly chosen
2066 * numbers. This cannot introduce any bias or restriction on
2067 * the available grids, since we already know those numbers
2068 * are all distinct so all we're doing is choosing their
2071 for (x
= 0; x
< cr
; x
++)
2073 shuffle(grid
, cr
, sizeof(*grid
), rs
);
2074 for (x
= 0; x
< cr
; x
++)
2075 gridgen_place(usage
, x
, 0, grid
[x
], TRUE
);
2077 usage
->spaces
= snewn(cr
* cr
, struct gridgen_coord
);
2083 * Initialise the list of grid spaces, taking care to leave
2084 * out the row I've already filled in above.
2086 for (y
= 1; y
< cr
; y
++) {
2087 for (x
= 0; x
< cr
; x
++) {
2088 usage
->spaces
[usage
->nspaces
].x
= x
;
2089 usage
->spaces
[usage
->nspaces
].y
= y
;
2090 usage
->spaces
[usage
->nspaces
].r
= random_bits(rs
, 31);
2096 * Run the real generator function.
2098 ret
= gridgen_real(usage
, grid
, &maxsteps
);
2101 * Clean up the usage structure now we have our answer.
2103 sfree(usage
->spaces
);
2112 /* ----------------------------------------------------------------------
2113 * End of grid generator code.
2117 * Check whether a grid contains a valid complete puzzle.
2119 static int check_valid(int cr
, struct block_structure
*blocks
, int xtype
,
2122 unsigned char *used
;
2125 used
= snewn(cr
, unsigned char);
2128 * Check that each row contains precisely one of everything.
2130 for (y
= 0; y
< cr
; y
++) {
2131 memset(used
, FALSE
, cr
);
2132 for (x
= 0; x
< cr
; x
++)
2133 if (grid
[y
*cr
+x
] > 0 && grid
[y
*cr
+x
] <= cr
)
2134 used
[grid
[y
*cr
+x
]-1] = TRUE
;
2135 for (n
= 0; n
< cr
; n
++)
2143 * Check that each column contains precisely one of everything.
2145 for (x
= 0; x
< cr
; x
++) {
2146 memset(used
, FALSE
, cr
);
2147 for (y
= 0; y
< cr
; y
++)
2148 if (grid
[y
*cr
+x
] > 0 && grid
[y
*cr
+x
] <= cr
)
2149 used
[grid
[y
*cr
+x
]-1] = TRUE
;
2150 for (n
= 0; n
< cr
; n
++)
2158 * Check that each block contains precisely one of everything.
2160 for (i
= 0; i
< cr
; i
++) {
2161 memset(used
, FALSE
, cr
);
2162 for (j
= 0; j
< cr
; j
++)
2163 if (grid
[blocks
->blocks
[i
][j
]] > 0 &&
2164 grid
[blocks
->blocks
[i
][j
]] <= cr
)
2165 used
[grid
[blocks
->blocks
[i
][j
]]-1] = TRUE
;
2166 for (n
= 0; n
< cr
; n
++)
2174 * Check that each diagonal contains precisely one of everything.
2177 memset(used
, FALSE
, cr
);
2178 for (i
= 0; i
< cr
; i
++)
2179 if (grid
[diag0(i
)] > 0 && grid
[diag0(i
)] <= cr
)
2180 used
[grid
[diag0(i
)]-1] = TRUE
;
2181 for (n
= 0; n
< cr
; n
++)
2186 for (i
= 0; i
< cr
; i
++)
2187 if (grid
[diag1(i
)] > 0 && grid
[diag1(i
)] <= cr
)
2188 used
[grid
[diag1(i
)]-1] = TRUE
;
2189 for (n
= 0; n
< cr
; n
++)
2200 static int symmetries(game_params
*params
, int x
, int y
, int *output
, int s
)
2202 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
2205 #define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
2211 break; /* just x,y is all we need */
2213 ADD(cr
- 1 - x
, cr
- 1 - y
);
2218 ADD(cr
- 1 - x
, cr
- 1 - y
);
2229 ADD(cr
- 1 - x
, cr
- 1 - y
);
2233 ADD(cr
- 1 - x
, cr
- 1 - y
);
2234 ADD(cr
- 1 - y
, cr
- 1 - x
);
2239 ADD(cr
- 1 - x
, cr
- 1 - y
);
2243 ADD(cr
- 1 - y
, cr
- 1 - x
);
2252 static char *encode_solve_move(int cr
, digit
*grid
)
2255 char *ret
, *p
, *sep
;
2258 * It's surprisingly easy to work out _exactly_ how long this
2259 * string needs to be. To decimal-encode all the numbers from 1
2262 * - every number has a units digit; total is n.
2263 * - all numbers above 9 have a tens digit; total is max(n-9,0).
2264 * - all numbers above 99 have a hundreds digit; total is max(n-99,0).
2268 for (i
= 1; i
<= cr
; i
*= 10)
2269 len
+= max(cr
- i
+ 1, 0);
2270 len
+= cr
; /* don't forget the commas */
2271 len
*= cr
; /* there are cr rows of these */
2274 * Now len is one bigger than the total size of the
2275 * comma-separated numbers (because we counted an
2276 * additional leading comma). We need to have a leading S
2277 * and a trailing NUL, so we're off by one in total.
2281 ret
= snewn(len
, char);
2285 for (i
= 0; i
< cr
*cr
; i
++) {
2286 p
+= sprintf(p
, "%s%d", sep
, grid
[i
]);
2290 assert(p
- ret
== len
);
2295 static char *new_game_desc(game_params
*params
, random_state
*rs
,
2296 char **aux
, int interactive
)
2298 int c
= params
->c
, r
= params
->r
, cr
= c
*r
;
2300 struct block_structure
*blocks
;
2301 digit
*grid
, *grid2
;
2302 struct xy
{ int x
, y
; } *locs
;
2305 int coords
[16], ncoords
;
2310 * Adjust the maximum difficulty level to be consistent with
2311 * the puzzle size: all 2x2 puzzles appear to be Trivial
2312 * (DIFF_BLOCK) so we cannot hold out for even a Basic
2313 * (DIFF_SIMPLE) one.
2315 maxdiff
= params
->diff
;
2316 if (c
== 2 && r
== 2)
2317 maxdiff
= DIFF_BLOCK
;
2319 grid
= snewn(area
, digit
);
2320 locs
= snewn(area
, struct xy
);
2321 grid2
= snewn(area
, digit
);
2323 blocks
= snew(struct block_structure
);
2324 blocks
->c
= params
->c
; blocks
->r
= params
->r
;
2325 blocks
->whichblock
= snewn(area
*2, int);
2326 blocks
->blocks
= snewn(cr
, int *);
2327 for (i
= 0; i
< cr
; i
++)
2328 blocks
->blocks
[i
] = blocks
->whichblock
+ area
+ i
*cr
;
2329 #ifdef STANDALONE_SOLVER
2330 assert(!"This should never happen, so we don't need to create blocknames");
2334 * Loop until we get a grid of the required difficulty. This is
2335 * nasty, but it seems to be unpleasantly hard to generate
2336 * difficult grids otherwise.
2340 * Generate a random solved state, starting by
2341 * constructing the block structure.
2343 if (r
== 1) { /* jigsaw mode */
2344 int *dsf
= divvy_rectangle(cr
, cr
, cr
, rs
);
2347 for (i
= 0; i
< area
; i
++)
2348 blocks
->whichblock
[i
] = -1;
2349 for (i
= 0; i
< area
; i
++) {
2350 int j
= dsf_canonify(dsf
, i
);
2351 if (blocks
->whichblock
[j
] < 0)
2352 blocks
->whichblock
[j
] = nb
++;
2353 blocks
->whichblock
[i
] = blocks
->whichblock
[j
];
2358 } else { /* basic Sudoku mode */
2359 for (y
= 0; y
< cr
; y
++)
2360 for (x
= 0; x
< cr
; x
++)
2361 blocks
->whichblock
[y
*cr
+x
] = (y
/c
) * c
+ (x
/r
);
2363 for (i
= 0; i
< cr
; i
++)
2364 blocks
->blocks
[i
][cr
-1] = 0;
2365 for (i
= 0; i
< area
; i
++) {
2366 int b
= blocks
->whichblock
[i
];
2367 j
= blocks
->blocks
[b
][cr
-1]++;
2369 blocks
->blocks
[b
][j
] = i
;
2372 if (!gridgen(cr
, blocks
, params
->xtype
, grid
, rs
, area
*area
))
2374 assert(check_valid(cr
, blocks
, params
->xtype
, grid
));
2377 * Save the solved grid in aux.
2381 * We might already have written *aux the last time we
2382 * went round this loop, in which case we should free
2383 * the old aux before overwriting it with the new one.
2389 *aux
= encode_solve_move(cr
, grid
);
2393 * Now we have a solved grid, start removing things from it
2394 * while preserving solubility.
2398 * Find the set of equivalence classes of squares permitted
2399 * by the selected symmetry. We do this by enumerating all
2400 * the grid squares which have no symmetric companion
2401 * sorting lower than themselves.
2404 for (y
= 0; y
< cr
; y
++)
2405 for (x
= 0; x
< cr
; x
++) {
2409 ncoords
= symmetries(params
, x
, y
, coords
, params
->symm
);
2410 for (j
= 0; j
< ncoords
; j
++)
2411 if (coords
[2*j
+1]*cr
+coords
[2*j
] < i
)
2421 * Now shuffle that list.
2423 shuffle(locs
, nlocs
, sizeof(*locs
), rs
);
2426 * Now loop over the shuffled list and, for each element,
2427 * see whether removing that element (and its reflections)
2428 * from the grid will still leave the grid soluble.
2430 for (i
= 0; i
< nlocs
; i
++) {
2436 memcpy(grid2
, grid
, area
);
2437 ncoords
= symmetries(params
, x
, y
, coords
, params
->symm
);
2438 for (j
= 0; j
< ncoords
; j
++)
2439 grid2
[coords
[2*j
+1]*cr
+coords
[2*j
]] = 0;
2441 ret
= solver(cr
, blocks
, params
->xtype
, grid2
, maxdiff
);
2442 if (ret
<= maxdiff
) {
2443 for (j
= 0; j
< ncoords
; j
++)
2444 grid
[coords
[2*j
+1]*cr
+coords
[2*j
]] = 0;
2448 memcpy(grid2
, grid
, area
);
2450 if (solver(cr
, blocks
, params
->xtype
, grid2
, maxdiff
) == maxdiff
)
2451 break; /* found one! */
2458 * Now we have the grid as it will be presented to the user.
2459 * Encode it in a game desc.
2465 desc
= snewn(7 * area
, char);
2468 for (i
= 0; i
<= area
; i
++) {
2469 int n
= (i
< area ? grid
[i
] : -1);
2476 int c
= 'a' - 1 + run
;
2480 run
-= c
- ('a' - 1);
2484 * If there's a number in the very top left or
2485 * bottom right, there's no point putting an
2486 * unnecessary _ before or after it.
2488 if (p
> desc
&& n
> 0)
2492 p
+= sprintf(p
, "%d", n
);
2503 * Encode the block structure. We do this by encoding
2504 * the pattern of dividing lines: first we iterate
2505 * over the cr*(cr-1) internal vertical grid lines in
2506 * ordinary reading order, then over the cr*(cr-1)
2507 * internal horizontal ones in transposed reading
2510 * We encode the number of non-lines between the
2511 * lines; _ means zero (two adjacent divisions), a
2512 * means 1, ..., y means 25, and z means 25 non-lines
2513 * _and no following line_ (so that za means 26, zb 27
2516 for (i
= 0; i
<= 2*cr
*(cr
-1); i
++) {
2519 if (i
== 2*cr
*(cr
-1)) {
2520 edge
= TRUE
; /* terminating virtual edge */
2522 if (i
< cr
*(cr
-1)) {
2533 edge
= (blocks
->whichblock
[p0
] != blocks
->whichblock
[p1
]);
2537 while (currrun
> 25)
2538 *p
++ = 'z', currrun
-= 25;
2540 *p
++ = 'a'-1 + currrun
;
2549 assert(p
- desc
< 7 * area
);
2551 desc
= sresize(desc
, p
- desc
, char);
2559 static char *validate_desc(game_params
*params
, char *desc
)
2561 int cr
= params
->c
* params
->r
, area
= cr
*cr
;
2565 while (*desc
&& *desc
!= ',') {
2567 if (n
>= 'a' && n
<= 'z') {
2568 squares
+= n
- 'a' + 1;
2569 } else if (n
== '_') {
2571 } else if (n
> '0' && n
<= '9') {
2572 int val
= atoi(desc
-1);
2573 if (val
< 1 || val
> params
->c
* params
->r
)
2574 return "Out-of-range number in game description";
2576 while (*desc
>= '0' && *desc
<= '9')
2579 return "Invalid character in game description";
2583 return "Not enough data to fill grid";
2586 return "Too much data to fit in grid";
2588 if (params
->r
== 1) {
2592 * Now we expect a suffix giving the jigsaw block
2593 * structure. Parse it and validate that it divides the
2594 * grid into the right number of regions which are the
2598 return "Expected jigsaw block structure in game description";
2601 dsf
= snew_dsf(area
);
2609 else if (*desc
>= 'a' && *desc
<= 'z')
2610 c
= *desc
- 'a' + 1;
2613 return "Invalid character in game description";
2617 adv
= (c
!= 25); /* 'z' is a special case */
2623 * Non-edge; merge the two dsf classes on either
2626 if (pos
>= 2*cr
*(cr
-1)) {
2628 return "Too much data in block structure specification";
2629 } else if (pos
< cr
*(cr
-1)) {
2635 int x
= pos
/(cr
-1) - cr
;
2640 dsf_merge(dsf
, p0
, p1
);
2649 * When desc is exhausted, we expect to have gone exactly
2650 * one space _past_ the end of the grid, due to the dummy
2653 if (pos
!= 2*cr
*(cr
-1)+1) {
2655 return "Not enough data in block structure specification";
2659 * Now we've got our dsf. Verify that it matches
2663 int *canons
, *counts
;
2664 int i
, j
, c
, ncanons
= 0;
2666 canons
= snewn(cr
, int);
2667 counts
= snewn(cr
, int);
2669 for (i
= 0; i
< area
; i
++) {
2670 j
= dsf_canonify(dsf
, i
);
2672 for (c
= 0; c
< ncanons
; c
++)
2673 if (canons
[c
] == j
) {
2675 if (counts
[c
] > cr
) {
2679 return "A jigsaw block is too big";
2685 if (ncanons
>= cr
) {
2689 return "Too many distinct jigsaw blocks";
2691 canons
[ncanons
] = j
;
2692 counts
[ncanons
] = 1;
2698 * If we've managed to get through that loop without
2699 * tripping either of the error conditions, then we
2700 * must have partitioned the entire grid into at most
2701 * cr blocks of at most cr squares each; therefore we
2702 * must have _exactly_ cr blocks of _exactly_ cr
2703 * squares each. I'll verify that by assertion just in
2704 * case something has gone horribly wrong, but it
2705 * shouldn't have been able to happen by duff input,
2706 * only by a bug in the above code.
2708 assert(ncanons
== cr
);
2709 for (c
= 0; c
< ncanons
; c
++)
2710 assert(counts
[c
] == cr
);
2719 return "Unexpected jigsaw block structure in game description";
2725 static game_state
*new_game(midend
*me
, game_params
*params
, char *desc
)
2727 game_state
*state
= snew(game_state
);
2728 int c
= params
->c
, r
= params
->r
, cr
= c
*r
, area
= cr
* cr
;
2732 state
->xtype
= params
->xtype
;
2734 state
->grid
= snewn(area
, digit
);
2735 state
->pencil
= snewn(area
* cr
, unsigned char);
2736 memset(state
->pencil
, 0, area
* cr
);
2737 state
->immutable
= snewn(area
, unsigned char);
2738 memset(state
->immutable
, FALSE
, area
);
2740 state
->blocks
= snew(struct block_structure
);
2741 state
->blocks
->c
= c
; state
->blocks
->r
= r
;
2742 state
->blocks
->refcount
= 1;
2743 state
->blocks
->whichblock
= snewn(area
*2, int);
2744 state
->blocks
->blocks
= snewn(cr
, int *);
2745 for (i
= 0; i
< cr
; i
++)
2746 state
->blocks
->blocks
[i
] = state
->blocks
->whichblock
+ area
+ i
*cr
;
2747 #ifdef STANDALONE_SOLVER
2748 state
->blocks
->blocknames
= (char **)smalloc(cr
*(sizeof(char *)+80));
2751 state
->completed
= state
->cheated
= FALSE
;
2754 while (*desc
&& *desc
!= ',') {
2756 if (n
>= 'a' && n
<= 'z') {
2757 int run
= n
- 'a' + 1;
2758 assert(i
+ run
<= area
);
2760 state
->grid
[i
++] = 0;
2761 } else if (n
== '_') {
2763 } else if (n
> '0' && n
<= '9') {
2765 state
->immutable
[i
] = TRUE
;
2766 state
->grid
[i
++] = atoi(desc
-1);
2767 while (*desc
>= '0' && *desc
<= '9')
2770 assert(!"We can't get here");
2780 assert(*desc
== ',');
2782 dsf
= snew_dsf(area
);
2790 else if (*desc
>= 'a' && *desc
<= 'z')
2791 c
= *desc
- 'a' + 1;
2793 assert(!"Shouldn't get here");
2796 adv
= (c
!= 25); /* 'z' is a special case */
2802 * Non-edge; merge the two dsf classes on either
2805 assert(pos
< 2*cr
*(cr
-1));
2806 if (pos
< cr
*(cr
-1)) {
2812 int x
= pos
/(cr
-1) - cr
;
2817 dsf_merge(dsf
, p0
, p1
);
2826 * When desc is exhausted, we expect to have gone exactly
2827 * one space _past_ the end of the grid, due to the dummy
2830 assert(pos
== 2*cr
*(cr
-1)+1);
2833 * Now we've got our dsf. Translate it into a block
2837 for (i
= 0; i
< area
; i
++)
2838 state
->blocks
->whichblock
[i
] = -1;
2839 for (i
= 0; i
< area
; i
++) {
2840 int j
= dsf_canonify(dsf
, i
);
2841 if (state
->blocks
->whichblock
[j
] < 0)
2842 state
->blocks
->whichblock
[j
] = nb
++;
2843 state
->blocks
->whichblock
[i
] = state
->blocks
->whichblock
[j
];
2853 for (y
= 0; y
< cr
; y
++)
2854 for (x
= 0; x
< cr
; x
++)
2855 state
->blocks
->whichblock
[y
*cr
+x
] = (y
/c
) * c
+ (x
/r
);
2859 * Having sorted out whichblock[], set up the block index arrays.
2861 for (i
= 0; i
< cr
; i
++)
2862 state
->blocks
->blocks
[i
][cr
-1] = 0;
2863 for (i
= 0; i
< area
; i
++) {
2864 int b
= state
->blocks
->whichblock
[i
];
2865 int j
= state
->blocks
->blocks
[b
][cr
-1]++;
2867 state
->blocks
->blocks
[b
][j
] = i
;
2870 #ifdef STANDALONE_SOLVER
2872 * Set up the block names for solver diagnostic output.
2875 char *p
= (char *)(state
->blocks
->blocknames
+ cr
);
2878 for (i
= 0; i
< cr
; i
++)
2879 state
->blocks
->blocknames
[i
] = NULL
;
2881 for (i
= 0; i
< area
; i
++) {
2882 int j
= state
->blocks
->whichblock
[i
];
2883 if (!state
->blocks
->blocknames
[j
]) {
2884 state
->blocks
->blocknames
[j
] = p
;
2885 p
+= 1 + sprintf(p
, "starting at (%d,%d)",
2886 1 + i
%cr
, 1 + i
/cr
);
2891 for (by
= 0; by
< r
; by
++)
2892 for (bx
= 0; bx
< c
; bx
++) {
2893 state
->blocks
->blocknames
[by
*c
+bx
] = p
;
2894 p
+= 1 + sprintf(p
, "(%d,%d)", bx
+1, by
+1);
2897 assert(p
- (char *)state
->blocks
->blocknames
< cr
*(sizeof(char *)+80));
2898 for (i
= 0; i
< cr
; i
++)
2899 assert(state
->blocks
->blocknames
[i
]);
2906 static game_state
*dup_game(game_state
*state
)
2908 game_state
*ret
= snew(game_state
);
2909 int cr
= state
->cr
, area
= cr
* cr
;
2911 ret
->cr
= state
->cr
;
2912 ret
->xtype
= state
->xtype
;
2914 ret
->blocks
= state
->blocks
;
2915 ret
->blocks
->refcount
++;
2917 ret
->grid
= snewn(area
, digit
);
2918 memcpy(ret
->grid
, state
->grid
, area
);
2920 ret
->pencil
= snewn(area
* cr
, unsigned char);
2921 memcpy(ret
->pencil
, state
->pencil
, area
* cr
);
2923 ret
->immutable
= snewn(area
, unsigned char);
2924 memcpy(ret
->immutable
, state
->immutable
, area
);
2926 ret
->completed
= state
->completed
;
2927 ret
->cheated
= state
->cheated
;
2932 static void free_game(game_state
*state
)
2934 if (--state
->blocks
->refcount
== 0) {
2935 sfree(state
->blocks
->whichblock
);
2936 sfree(state
->blocks
->blocks
);
2937 #ifdef STANDALONE_SOLVER
2938 sfree(state
->blocks
->blocknames
);
2940 sfree(state
->blocks
);
2942 sfree(state
->immutable
);
2943 sfree(state
->pencil
);
2948 static char *solve_game(game_state
*state
, game_state
*currstate
,
2949 char *ai
, char **error
)
2957 * If we already have the solution in ai, save ourselves some
2963 grid
= snewn(cr
*cr
, digit
);
2964 memcpy(grid
, state
->grid
, cr
*cr
);
2965 solve_ret
= solver(cr
, state
->blocks
, state
->xtype
, grid
, DIFF_RECURSIVE
);
2969 if (solve_ret
== DIFF_IMPOSSIBLE
)
2970 *error
= "No solution exists for this puzzle";
2971 else if (solve_ret
== DIFF_AMBIGUOUS
)
2972 *error
= "Multiple solutions exist for this puzzle";
2979 ret
= encode_solve_move(cr
, grid
);
2986 static char *grid_text_format(int cr
, struct block_structure
*blocks
,
2987 int xtype
, digit
*grid
)
2991 int totallen
, linelen
, nlines
;
2995 * For non-jigsaw Sudoku, we format in the way we always have,
2996 * by having the digits unevenly spaced so that the dividing
3005 * For jigsaw puzzles, however, we must leave space between
3006 * _all_ pairs of digits for an optional dividing line, so we
3007 * have to move to the rather ugly
3017 * We deal with both cases using the same formatting code; we
3018 * simply invent a vmod value such that there's a vertical
3019 * dividing line before column i iff i is divisible by vmod
3020 * (so it's r in the first case and 1 in the second), and hmod
3021 * likewise for horizontal dividing lines.
3024 if (blocks
->r
!= 1) {
3032 * Line length: we have cr digits, each with a space after it,
3033 * and (cr-1)/vmod dividing lines, each with a space after it.
3034 * The final space is replaced by a newline, but that doesn't
3035 * affect the length.
3037 linelen
= 2*(cr
+ (cr
-1)/vmod
);
3040 * Number of lines: we have cr rows of digits, and (cr-1)/hmod
3043 nlines
= cr
+ (cr
-1)/hmod
;
3046 * Allocate the space.
3048 totallen
= linelen
* nlines
;
3049 ret
= snewn(totallen
+1, char); /* leave room for terminating NUL */
3055 for (y
= 0; y
< cr
; y
++) {
3059 for (x
= 0; x
< cr
; x
++) {
3063 digit d
= grid
[y
*cr
+x
];
3067 * Empty space: we usually write a dot, but we'll
3068 * highlight spaces on the X-diagonals (in X mode)
3069 * by using underscores instead.
3071 if (xtype
&& (ondiag0(y
*cr
+x
) || ondiag1(y
*cr
+x
)))
3075 } else if (d
<= 9) {
3092 * Optional dividing line.
3094 if (blocks
->whichblock
[y
*cr
+x
] != blocks
->whichblock
[y
*cr
+x
+1])
3101 if (y
== cr
-1 || (y
+1) % hmod
)
3107 for (x
= 0; x
< cr
; x
++) {
3112 * Division between two squares. This varies
3113 * complicatedly in length.
3115 dwid
= 2; /* digit and its following space */
3117 dwid
--; /* no following space at end of line */
3118 if (x
> 0 && x
% vmod
== 0)
3119 dwid
++; /* preceding space after a divider */
3121 if (blocks
->whichblock
[y
*cr
+x
] != blocks
->whichblock
[(y
+1)*cr
+x
])
3138 * Corner square. This is:
3139 * - a space if all four surrounding squares are in
3141 * - a vertical line if the two left ones are in one
3142 * block and the two right in another
3143 * - a horizontal line if the two top ones are in one
3144 * block and the two bottom in another
3145 * - a plus sign in all other cases. (If we had a
3146 * richer character set available we could break
3147 * this case up further by doing fun things with
3148 * line-drawing T-pieces.)
3150 tl
= blocks
->whichblock
[y
*cr
+x
];
3151 tr
= blocks
->whichblock
[y
*cr
+x
+1];
3152 bl
= blocks
->whichblock
[(y
+1)*cr
+x
];
3153 br
= blocks
->whichblock
[(y
+1)*cr
+x
+1];
3155 if (tl
== tr
&& tr
== bl
&& bl
== br
)
3157 else if (tl
== bl
&& tr
== br
)
3159 else if (tl
== tr
&& bl
== br
)
3168 assert(p
- ret
== totallen
);
3173 static char *game_text_format(game_state
*state
)
3175 return grid_text_format(state
->cr
, state
->blocks
, state
->xtype
,
3181 * These are the coordinates of the currently highlighted
3182 * square on the grid, or -1,-1 if there isn't one. When there
3183 * is, pressing a valid number or letter key or Space will
3184 * enter that number or letter in the grid.
3188 * This indicates whether the current highlight is a
3189 * pencil-mark one or a real one.
3194 static game_ui
*new_ui(game_state
*state
)
3196 game_ui
*ui
= snew(game_ui
);
3198 ui
->hx
= ui
->hy
= -1;
3204 static void free_ui(game_ui
*ui
)
3209 static char *encode_ui(game_ui
*ui
)
3214 static void decode_ui(game_ui
*ui
, char *encoding
)
3218 static void game_changed_state(game_ui
*ui
, game_state
*oldstate
,
3219 game_state
*newstate
)
3221 int cr
= newstate
->cr
;
3223 * We prevent pencil-mode highlighting of a filled square. So
3224 * if the user has just filled in a square which we had a
3225 * pencil-mode highlight in (by Undo, or by Redo, or by Solve),
3226 * then we cancel the highlight.
3228 if (ui
->hx
>= 0 && ui
->hy
>= 0 && ui
->hpencil
&&
3229 newstate
->grid
[ui
->hy
* cr
+ ui
->hx
] != 0) {
3230 ui
->hx
= ui
->hy
= -1;
3234 struct game_drawstate
{
3239 unsigned char *pencil
;
3241 /* This is scratch space used within a single call to game_redraw. */
3245 static char *interpret_move(game_state
*state
, game_ui
*ui
, game_drawstate
*ds
,
3246 int x
, int y
, int button
)
3252 button
&= ~MOD_MASK
;
3254 tx
= (x
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
3255 ty
= (y
+ TILE_SIZE
- BORDER
) / TILE_SIZE
- 1;
3257 if (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
) {
3258 if (button
== LEFT_BUTTON
) {
3259 if (state
->immutable
[ty
*cr
+tx
]) {
3260 ui
->hx
= ui
->hy
= -1;
3261 } else if (tx
== ui
->hx
&& ty
== ui
->hy
&& ui
->hpencil
== 0) {
3262 ui
->hx
= ui
->hy
= -1;
3268 return ""; /* UI activity occurred */
3270 if (button
== RIGHT_BUTTON
) {
3272 * Pencil-mode highlighting for non filled squares.
3274 if (state
->grid
[ty
*cr
+tx
] == 0) {
3275 if (tx
== ui
->hx
&& ty
== ui
->hy
&& ui
->hpencil
) {
3276 ui
->hx
= ui
->hy
= -1;
3283 ui
->hx
= ui
->hy
= -1;
3285 return ""; /* UI activity occurred */
3289 if (ui
->hx
!= -1 && ui
->hy
!= -1 &&
3290 ((button
>= '1' && button
<= '9' && button
- '0' <= cr
) ||
3291 (button
>= 'a' && button
<= 'z' && button
- 'a' + 10 <= cr
) ||
3292 (button
>= 'A' && button
<= 'Z' && button
- 'A' + 10 <= cr
) ||
3293 button
== ' ' || button
== '\010' || button
== '\177')) {
3294 int n
= button
- '0';
3295 if (button
>= 'A' && button
<= 'Z')
3296 n
= button
- 'A' + 10;
3297 if (button
>= 'a' && button
<= 'z')
3298 n
= button
- 'a' + 10;
3299 if (button
== ' ' || button
== '\010' || button
== '\177')
3303 * Can't overwrite this square. In principle this shouldn't
3304 * happen anyway because we should never have even been
3305 * able to highlight the square, but it never hurts to be
3308 if (state
->immutable
[ui
->hy
*cr
+ui
->hx
])
3312 * Can't make pencil marks in a filled square. In principle
3313 * this shouldn't happen anyway because we should never
3314 * have even been able to pencil-highlight the square, but
3315 * it never hurts to be careful.
3317 if (ui
->hpencil
&& state
->grid
[ui
->hy
*cr
+ui
->hx
])
3320 sprintf(buf
, "%c%d,%d,%d",
3321 (char)(ui
->hpencil
&& n
> 0 ?
'P' : 'R'), ui
->hx
, ui
->hy
, n
);
3323 ui
->hx
= ui
->hy
= -1;
3331 static game_state
*execute_move(game_state
*from
, char *move
)
3337 if (move
[0] == 'S') {
3340 ret
= dup_game(from
);
3341 ret
->completed
= ret
->cheated
= TRUE
;
3344 for (n
= 0; n
< cr
*cr
; n
++) {
3345 ret
->grid
[n
] = atoi(p
);
3347 if (!*p
|| ret
->grid
[n
] < 1 || ret
->grid
[n
] > cr
) {
3352 while (*p
&& isdigit((unsigned char)*p
)) p
++;
3357 } else if ((move
[0] == 'P' || move
[0] == 'R') &&
3358 sscanf(move
+1, "%d,%d,%d", &x
, &y
, &n
) == 3 &&
3359 x
>= 0 && x
< cr
&& y
>= 0 && y
< cr
&& n
>= 0 && n
<= cr
) {
3361 ret
= dup_game(from
);
3362 if (move
[0] == 'P' && n
> 0) {
3363 int index
= (y
*cr
+x
) * cr
+ (n
-1);
3364 ret
->pencil
[index
] = !ret
->pencil
[index
];
3366 ret
->grid
[y
*cr
+x
] = n
;
3367 memset(ret
->pencil
+ (y
*cr
+x
)*cr
, 0, cr
);
3370 * We've made a real change to the grid. Check to see
3371 * if the game has been completed.
3373 if (!ret
->completed
&& check_valid(cr
, ret
->blocks
, ret
->xtype
,
3375 ret
->completed
= TRUE
;
3380 return NULL
; /* couldn't parse move string */
3383 /* ----------------------------------------------------------------------
3387 #define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
3388 #define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
3390 static void game_compute_size(game_params
*params
, int tilesize
,
3393 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3394 struct { int tilesize
; } ads
, *ds
= &ads
;
3395 ads
.tilesize
= tilesize
;
3397 *x
= SIZE(params
->c
* params
->r
);
3398 *y
= SIZE(params
->c
* params
->r
);
3401 static void game_set_size(drawing
*dr
, game_drawstate
*ds
,
3402 game_params
*params
, int tilesize
)
3404 ds
->tilesize
= tilesize
;
3407 static float *game_colours(frontend
*fe
, int *ncolours
)
3409 float *ret
= snewn(3 * NCOLOURS
, float);
3411 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
3413 ret
[COL_XDIAGONALS
* 3 + 0] = 0.9F
* ret
[COL_BACKGROUND
* 3 + 0];
3414 ret
[COL_XDIAGONALS
* 3 + 1] = 0.9F
* ret
[COL_BACKGROUND
* 3 + 1];
3415 ret
[COL_XDIAGONALS
* 3 + 2] = 0.9F
* ret
[COL_BACKGROUND
* 3 + 2];
3417 ret
[COL_GRID
* 3 + 0] = 0.0F
;
3418 ret
[COL_GRID
* 3 + 1] = 0.0F
;
3419 ret
[COL_GRID
* 3 + 2] = 0.0F
;
3421 ret
[COL_CLUE
* 3 + 0] = 0.0F
;
3422 ret
[COL_CLUE
* 3 + 1] = 0.0F
;
3423 ret
[COL_CLUE
* 3 + 2] = 0.0F
;
3425 ret
[COL_USER
* 3 + 0] = 0.0F
;
3426 ret
[COL_USER
* 3 + 1] = 0.6F
* ret
[COL_BACKGROUND
* 3 + 1];
3427 ret
[COL_USER
* 3 + 2] = 0.0F
;
3429 ret
[COL_HIGHLIGHT
* 3 + 0] = 0.78F
* ret
[COL_BACKGROUND
* 3 + 0];
3430 ret
[COL_HIGHLIGHT
* 3 + 1] = 0.78F
* ret
[COL_BACKGROUND
* 3 + 1];
3431 ret
[COL_HIGHLIGHT
* 3 + 2] = 0.78F
* ret
[COL_BACKGROUND
* 3 + 2];
3433 ret
[COL_ERROR
* 3 + 0] = 1.0F
;
3434 ret
[COL_ERROR
* 3 + 1] = 0.0F
;
3435 ret
[COL_ERROR
* 3 + 2] = 0.0F
;
3437 ret
[COL_PENCIL
* 3 + 0] = 0.5F
* ret
[COL_BACKGROUND
* 3 + 0];
3438 ret
[COL_PENCIL
* 3 + 1] = 0.5F
* ret
[COL_BACKGROUND
* 3 + 1];
3439 ret
[COL_PENCIL
* 3 + 2] = ret
[COL_BACKGROUND
* 3 + 2];
3441 *ncolours
= NCOLOURS
;
3445 static game_drawstate
*game_new_drawstate(drawing
*dr
, game_state
*state
)
3447 struct game_drawstate
*ds
= snew(struct game_drawstate
);
3450 ds
->started
= FALSE
;
3452 ds
->xtype
= state
->xtype
;
3453 ds
->grid
= snewn(cr
*cr
, digit
);
3454 memset(ds
->grid
, cr
+2, cr
*cr
);
3455 ds
->pencil
= snewn(cr
*cr
*cr
, digit
);
3456 memset(ds
->pencil
, 0, cr
*cr
*cr
);
3457 ds
->hl
= snewn(cr
*cr
, unsigned char);
3458 memset(ds
->hl
, 0, cr
*cr
);
3459 ds
->entered_items
= snewn(cr
*cr
, int);
3460 ds
->tilesize
= 0; /* not decided yet */
3464 static void game_free_drawstate(drawing
*dr
, game_drawstate
*ds
)
3469 sfree(ds
->entered_items
);
3473 static void draw_number(drawing
*dr
, game_drawstate
*ds
, game_state
*state
,
3474 int x
, int y
, int hl
)
3481 if (ds
->grid
[y
*cr
+x
] == state
->grid
[y
*cr
+x
] &&
3482 ds
->hl
[y
*cr
+x
] == hl
&&
3483 !memcmp(ds
->pencil
+(y
*cr
+x
)*cr
, state
->pencil
+(y
*cr
+x
)*cr
, cr
))
3484 return; /* no change required */
3486 tx
= BORDER
+ x
* TILE_SIZE
+ 1 + GRIDEXTRA
;
3487 ty
= BORDER
+ y
* TILE_SIZE
+ 1 + GRIDEXTRA
;
3491 cw
= TILE_SIZE
-1-2*GRIDEXTRA
;
3492 ch
= TILE_SIZE
-1-2*GRIDEXTRA
;
3494 if (x
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[y
*cr
+x
-1])
3495 cx
-= GRIDEXTRA
, cw
+= GRIDEXTRA
;
3496 if (x
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[y
*cr
+x
+1])
3498 if (y
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[(y
-1)*cr
+x
])
3499 cy
-= GRIDEXTRA
, ch
+= GRIDEXTRA
;
3500 if (y
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] == state
->blocks
->whichblock
[(y
+1)*cr
+x
])
3503 clip(dr
, cx
, cy
, cw
, ch
);
3505 /* background needs erasing */
3506 draw_rect(dr
, cx
, cy
, cw
, ch
,
3507 ((hl
& 15) == 1 ? COL_HIGHLIGHT
:
3508 (ds
->xtype
&& (ondiag0(y
*cr
+x
) || ondiag1(y
*cr
+x
))) ? COL_XDIAGONALS
:
3512 * Draw the corners of thick lines in corner-adjacent squares,
3513 * which jut into this square by one pixel.
3515 if (x
> 0 && y
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
-1)*cr
+x
-1])
3516 draw_rect(dr
, tx
-GRIDEXTRA
, ty
-GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
3517 if (x
+1 < cr
&& y
> 0 && state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
-1)*cr
+x
+1])
3518 draw_rect(dr
, tx
+TILE_SIZE
-1-2*GRIDEXTRA
, ty
-GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
3519 if (x
> 0 && y
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
+1)*cr
+x
-1])
3520 draw_rect(dr
, tx
-GRIDEXTRA
, ty
+TILE_SIZE
-1-2*GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
3521 if (x
+1 < cr
&& y
+1 < cr
&& state
->blocks
->whichblock
[y
*cr
+x
] != state
->blocks
->whichblock
[(y
+1)*cr
+x
+1])
3522 draw_rect(dr
, tx
+TILE_SIZE
-1-2*GRIDEXTRA
, ty
+TILE_SIZE
-1-2*GRIDEXTRA
, GRIDEXTRA
, GRIDEXTRA
, COL_GRID
);
3524 /* pencil-mode highlight */
3525 if ((hl
& 15) == 2) {
3529 coords
[2] = cx
+cw
/2;
3532 coords
[5] = cy
+ch
/2;
3533 draw_polygon(dr
, coords
, 3, COL_HIGHLIGHT
, COL_HIGHLIGHT
);
3536 /* new number needs drawing? */
3537 if (state
->grid
[y
*cr
+x
]) {
3539 str
[0] = state
->grid
[y
*cr
+x
] + '0';
3541 str
[0] += 'a' - ('9'+1);
3542 draw_text(dr
, tx
+ TILE_SIZE
/2, ty
+ TILE_SIZE
/2,
3543 FONT_VARIABLE
, TILE_SIZE
/2, ALIGN_VCENTRE
| ALIGN_HCENTRE
,
3544 state
->immutable
[y
*cr
+x
] ? COL_CLUE
: (hl
& 16) ? COL_ERROR
: COL_USER
, str
);
3547 int pw
, ph
, pmax
, fontsize
;
3549 /* count the pencil marks required */
3550 for (i
= npencil
= 0; i
< cr
; i
++)
3551 if (state
->pencil
[(y
*cr
+x
)*cr
+i
])
3555 * It's not sensible to arrange pencil marks in the same
3556 * layout as the squares within a block, because this leads
3557 * to the font being too small. Instead, we arrange pencil
3558 * marks in the nearest thing we can to a square layout,
3559 * and we adjust the square layout depending on the number
3560 * of pencil marks in the square.
3562 for (pw
= 1; pw
* pw
< npencil
; pw
++);
3563 if (pw
< 3) pw
= 3; /* otherwise it just looks _silly_ */
3564 ph
= (npencil
+ pw
- 1) / pw
;
3565 if (ph
< 2) ph
= 2; /* likewise */
3567 fontsize
= TILE_SIZE
/(pmax
*(11-pmax
)/8);
3569 for (i
= j
= 0; i
< cr
; i
++)
3570 if (state
->pencil
[(y
*cr
+x
)*cr
+i
]) {
3571 int dx
= j
% pw
, dy
= j
/ pw
;
3576 str
[0] += 'a' - ('9'+1);
3577 draw_text(dr
, tx
+ (4*dx
+3) * TILE_SIZE
/ (4*pw
+2),
3578 ty
+ (4*dy
+3) * TILE_SIZE
/ (4*ph
+2),
3579 FONT_VARIABLE
, fontsize
,
3580 ALIGN_VCENTRE
| ALIGN_HCENTRE
, COL_PENCIL
, str
);
3587 draw_update(dr
, cx
, cy
, cw
, ch
);
3589 ds
->grid
[y
*cr
+x
] = state
->grid
[y
*cr
+x
];
3590 memcpy(ds
->pencil
+(y
*cr
+x
)*cr
, state
->pencil
+(y
*cr
+x
)*cr
, cr
);
3591 ds
->hl
[y
*cr
+x
] = hl
;
3594 static void game_redraw(drawing
*dr
, game_drawstate
*ds
, game_state
*oldstate
,
3595 game_state
*state
, int dir
, game_ui
*ui
,
3596 float animtime
, float flashtime
)
3603 * The initial contents of the window are not guaranteed
3604 * and can vary with front ends. To be on the safe side,
3605 * all games should start by drawing a big
3606 * background-colour rectangle covering the whole window.
3608 draw_rect(dr
, 0, 0, SIZE(cr
), SIZE(cr
), COL_BACKGROUND
);
3611 * Draw the grid. We draw it as a big thick rectangle of
3612 * COL_GRID initially; individual calls to draw_number()
3613 * will poke the right-shaped holes in it.
3615 draw_rect(dr
, BORDER
-GRIDEXTRA
, BORDER
-GRIDEXTRA
,
3616 cr
*TILE_SIZE
+1+2*GRIDEXTRA
, cr
*TILE_SIZE
+1+2*GRIDEXTRA
,
3621 * This array is used to keep track of rows, columns and boxes
3622 * which contain a number more than once.
3624 for (x
= 0; x
< cr
* cr
; x
++)
3625 ds
->entered_items
[x
] = 0;
3626 for (x
= 0; x
< cr
; x
++)
3627 for (y
= 0; y
< cr
; y
++) {
3628 digit d
= state
->grid
[y
*cr
+x
];
3630 int box
= state
->blocks
->whichblock
[y
*cr
+x
];
3631 ds
->entered_items
[x
*cr
+d
-1] |= ((ds
->entered_items
[x
*cr
+d
-1] & 1) << 1) | 1;
3632 ds
->entered_items
[y
*cr
+d
-1] |= ((ds
->entered_items
[y
*cr
+d
-1] & 4) << 1) | 4;
3633 ds
->entered_items
[box
*cr
+d
-1] |= ((ds
->entered_items
[box
*cr
+d
-1] & 16) << 1) | 16;
3635 if (ondiag0(y
*cr
+x
))
3636 ds
->entered_items
[d
-1] |= ((ds
->entered_items
[d
-1] & 64) << 1) | 64;
3637 if (ondiag1(y
*cr
+x
))
3638 ds
->entered_items
[cr
+d
-1] |= ((ds
->entered_items
[cr
+d
-1] & 64) << 1) | 64;
3644 * Draw any numbers which need redrawing.
3646 for (x
= 0; x
< cr
; x
++) {
3647 for (y
= 0; y
< cr
; y
++) {
3649 digit d
= state
->grid
[y
*cr
+x
];
3651 if (flashtime
> 0 &&
3652 (flashtime
<= FLASH_TIME
/3 ||
3653 flashtime
>= FLASH_TIME
*2/3))
3656 /* Highlight active input areas. */
3657 if (x
== ui
->hx
&& y
== ui
->hy
)
3658 highlight
= ui
->hpencil ?
2 : 1;
3660 /* Mark obvious errors (ie, numbers which occur more than once
3661 * in a single row, column, or box). */
3662 if (d
&& ((ds
->entered_items
[x
*cr
+d
-1] & 2) ||
3663 (ds
->entered_items
[y
*cr
+d
-1] & 8) ||
3664 (ds
->entered_items
[state
->blocks
->whichblock
[y
*cr
+x
]*cr
+d
-1] & 32) ||
3665 (ds
->xtype
&& ((ondiag0(y
*cr
+x
) && (ds
->entered_items
[d
-1] & 128)) ||
3666 (ondiag1(y
*cr
+x
) && (ds
->entered_items
[cr
+d
-1] & 128))))))
3669 draw_number(dr
, ds
, state
, x
, y
, highlight
);
3674 * Update the _entire_ grid if necessary.
3677 draw_update(dr
, 0, 0, SIZE(cr
), SIZE(cr
));
3682 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
3683 int dir
, game_ui
*ui
)
3688 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
3689 int dir
, game_ui
*ui
)
3691 if (!oldstate
->completed
&& newstate
->completed
&&
3692 !oldstate
->cheated
&& !newstate
->cheated
)
3697 static int game_timing_state(game_state
*state
, game_ui
*ui
)
3702 static void game_print_size(game_params
*params
, float *x
, float *y
)
3707 * I'll use 9mm squares by default. They should be quite big
3708 * for this game, because players will want to jot down no end
3709 * of pencil marks in the squares.
3711 game_compute_size(params
, 900, &pw
, &ph
);
3716 static void game_print(drawing
*dr
, game_state
*state
, int tilesize
)
3719 int ink
= print_mono_colour(dr
, 0);
3722 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3723 game_drawstate ads
, *ds
= &ads
;
3724 game_set_size(dr
, ds
, NULL
, tilesize
);
3729 print_line_width(dr
, 3 * TILE_SIZE
/ 40);
3730 draw_rect_outline(dr
, BORDER
, BORDER
, cr
*TILE_SIZE
, cr
*TILE_SIZE
, ink
);
3733 * Highlight X-diagonal squares.
3737 int xhighlight
= print_grey_colour(dr
, 0.90F
);
3739 for (i
= 0; i
< cr
; i
++)
3740 draw_rect(dr
, BORDER
+ i
*TILE_SIZE
, BORDER
+ i
*TILE_SIZE
,
3741 TILE_SIZE
, TILE_SIZE
, xhighlight
);
3742 for (i
= 0; i
< cr
; i
++)
3743 if (i
*2 != cr
-1) /* avoid redoing centre square, just for fun */
3744 draw_rect(dr
, BORDER
+ i
*TILE_SIZE
,
3745 BORDER
+ (cr
-1-i
)*TILE_SIZE
,
3746 TILE_SIZE
, TILE_SIZE
, xhighlight
);
3752 for (x
= 1; x
< cr
; x
++) {
3753 print_line_width(dr
, TILE_SIZE
/ 40);
3754 draw_line(dr
, BORDER
+x
*TILE_SIZE
, BORDER
,
3755 BORDER
+x
*TILE_SIZE
, BORDER
+cr
*TILE_SIZE
, ink
);
3757 for (y
= 1; y
< cr
; y
++) {
3758 print_line_width(dr
, TILE_SIZE
/ 40);
3759 draw_line(dr
, BORDER
, BORDER
+y
*TILE_SIZE
,
3760 BORDER
+cr
*TILE_SIZE
, BORDER
+y
*TILE_SIZE
, ink
);
3764 * Thick lines between cells. In order to do this using the
3765 * line-drawing rather than rectangle-drawing API (so as to
3766 * get line thicknesses to scale correctly) and yet have
3767 * correctly mitred joins between lines, we must do this by
3768 * tracing the boundary of each sub-block and drawing it in
3769 * one go as a single polygon.
3774 int x
, y
, dx
, dy
, sx
, sy
, sdx
, sdy
;
3776 print_line_width(dr
, 3 * TILE_SIZE
/ 40);
3779 * Maximum perimeter of a k-omino is 2k+2. (Proof: start
3780 * with k unconnected squares, with total perimeter 4k.
3781 * Now repeatedly join two disconnected components
3782 * together into a larger one; every time you do so you
3783 * remove at least two unit edges, and you require k-1 of
3784 * these operations to create a single connected piece, so
3785 * you must have at most 4k-2(k-1) = 2k+2 unit edges left
3788 coords
= snewn(4*cr
+4, int); /* 2k+2 points, 2 coords per point */
3791 * Iterate over all the blocks.
3793 for (bi
= 0; bi
< cr
; bi
++) {
3796 * For each block, find a starting square within it
3797 * which has a boundary at the left.
3799 for (i
= 0; i
< cr
; i
++) {
3800 int j
= state
->blocks
->blocks
[bi
][i
];
3801 if (j
% cr
== 0 || state
->blocks
->whichblock
[j
-1] != bi
)
3804 assert(i
< cr
); /* every block must have _some_ leftmost square */
3805 x
= state
->blocks
->blocks
[bi
][i
] % cr
;
3806 y
= state
->blocks
->blocks
[bi
][i
] / cr
;
3811 * Now begin tracing round the perimeter. At all
3812 * times, (x,y) describes some square within the
3813 * block, and (x+dx,y+dy) is some adjacent square
3814 * outside it; so the edge between those two squares
3815 * is always an edge of the block.
3817 sx
= x
, sy
= y
, sdx
= dx
, sdy
= dy
; /* save starting position */
3820 int cx
, cy
, tx
, ty
, nin
;
3823 * To begin with, record the point at one end of
3824 * the edge. To do this, we translate (x,y) down
3825 * and right by half a unit (so they're describing
3826 * a point in the _centre_ of the square) and then
3827 * translate back again in a manner rotated by dy
3831 cx
= ((2*x
+1) + dy
+ dx
) / 2;
3832 cy
= ((2*y
+1) - dx
+ dy
) / 2;
3833 coords
[2*n
+0] = BORDER
+ cx
* TILE_SIZE
;
3834 coords
[2*n
+1] = BORDER
+ cy
* TILE_SIZE
;
3838 * Now advance to the next edge, by looking at the
3839 * two squares beyond it. If they're both outside
3840 * the block, we turn right (by leaving x,y the
3841 * same and rotating dx,dy clockwise); if they're
3842 * both inside, we turn left (by rotating dx,dy
3843 * anticlockwise and contriving to leave x+dx,y+dy
3844 * unchanged); if one of each, we go straight on
3845 * (and may enforce by assertion that they're one
3846 * of each the _right_ way round).
3851 nin
+= (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
&&
3852 state
->blocks
->whichblock
[ty
*cr
+tx
] == bi
);
3855 nin
+= (tx
>= 0 && tx
< cr
&& ty
>= 0 && ty
< cr
&&
3856 state
->blocks
->whichblock
[ty
*cr
+tx
] == bi
);
3865 } else if (nin
== 2) {
3889 * Now enforce by assertion that we ended up
3890 * somewhere sensible.
3892 assert(x
>= 0 && x
< cr
&& y
>= 0 && y
< cr
&&
3893 state
->blocks
->whichblock
[y
*cr
+x
] == bi
);
3894 assert(x
+dx
< 0 || x
+dx
>= cr
|| y
+dy
< 0 || y
+dy
>= cr
||
3895 state
->blocks
->whichblock
[(y
+dy
)*cr
+(x
+dx
)] != bi
);
3897 } while (x
!= sx
|| y
!= sy
|| dx
!= sdx
|| dy
!= sdy
);
3900 * That's our polygon; now draw it.
3902 draw_polygon(dr
, coords
, n
, -1, ink
);
3911 for (y
= 0; y
< cr
; y
++)
3912 for (x
= 0; x
< cr
; x
++)
3913 if (state
->grid
[y
*cr
+x
]) {
3916 str
[0] = state
->grid
[y
*cr
+x
] + '0';
3918 str
[0] += 'a' - ('9'+1);
3919 draw_text(dr
, BORDER
+ x
*TILE_SIZE
+ TILE_SIZE
/2,
3920 BORDER
+ y
*TILE_SIZE
+ TILE_SIZE
/2,
3921 FONT_VARIABLE
, TILE_SIZE
/2,
3922 ALIGN_VCENTRE
| ALIGN_HCENTRE
, ink
, str
);
3927 #define thegame solo
3930 const struct game thegame
= {
3931 "Solo", "games.solo", "solo",
3938 TRUE
, game_configure
, custom_params
,
3946 TRUE
, game_text_format
,
3954 PREFERRED_TILE_SIZE
, game_compute_size
, game_set_size
,
3957 game_free_drawstate
,
3961 TRUE
, FALSE
, game_print_size
, game_print
,
3962 FALSE
, /* wants_statusbar */
3963 FALSE
, game_timing_state
,
3964 REQUIRE_RBUTTON
| REQUIRE_NUMPAD
, /* flags */
3967 #ifdef STANDALONE_SOLVER
3969 int main(int argc
, char **argv
)
3973 char *id
= NULL
, *desc
, *err
;
3977 while (--argc
> 0) {
3979 if (!strcmp(p
, "-v")) {
3980 solver_show_working
= TRUE
;
3981 } else if (!strcmp(p
, "-g")) {
3983 } else if (*p
== '-') {
3984 fprintf(stderr
, "%s: unrecognised option `%s'\n", argv
[0], p
);
3992 fprintf(stderr
, "usage: %s [-g | -v] <game_id>\n", argv
[0]);
3996 desc
= strchr(id
, ':');
3998 fprintf(stderr
, "%s: game id expects a colon in it\n", argv
[0]);
4003 p
= default_params();
4004 decode_params(p
, id
);
4005 err
= validate_desc(p
, desc
);
4007 fprintf(stderr
, "%s: %s\n", argv
[0], err
);
4010 s
= new_game(NULL
, p
, desc
);
4012 ret
= solver(s
->cr
, s
->blocks
, s
->xtype
, s
->grid
, DIFF_RECURSIVE
);
4014 printf("Difficulty rating: %s\n",
4015 ret
==DIFF_BLOCK ?
"Trivial (blockwise positional elimination only)":
4016 ret
==DIFF_SIMPLE ?
"Basic (row/column/number elimination required)":
4017 ret
==DIFF_INTERSECT ?
"Intermediate (intersectional analysis required)":
4018 ret
==DIFF_SET ?
"Advanced (set elimination required)":
4019 ret
==DIFF_EXTREME ?
"Extreme (complex non-recursive techniques required)":
4020 ret
==DIFF_RECURSIVE ?
"Unreasonable (guesswork and backtracking required)":
4021 ret
==DIFF_AMBIGUOUS ?
"Ambiguous (multiple solutions exist)":
4022 ret
==DIFF_IMPOSSIBLE ?
"Impossible (no solution exists)":
4023 "INTERNAL ERROR: unrecognised difficulty code");
4025 printf("%s\n", grid_text_format(s
->cr
, s
->blocks
, s
->xtype
, s
->grid
));