Hmm. Telling xvfb to default to a TrueColor visual did help, in that
[sgt/puzzles] / solo.c
CommitLineData
1d8e8ad8 1/*
2 * solo.c: the number-placing puzzle most popularly known as `Sudoku'.
3 *
4 * TODO:
5 *
c8266e03 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
16 * for
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
19 * them
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.
29 *
ef57b17d 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.
1d8e8ad8 36 *
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
46 * to confuse the two.
c8266e03 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.
1d8e8ad8 54 */
55
56/*
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:
63 *
64 * 4 5 1 | 2 6 3
65 * 6 3 2 | 5 4 1
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.)
70 * 5 1 4 | 3 2 6
71 * 2 6 3 | 1 5 4
72 *
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
79 * 2).
80 *
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.
83 */
84
85#include <stdio.h>
86#include <stdlib.h>
87#include <string.h>
88#include <assert.h>
89#include <ctype.h>
90#include <math.h>
91
7c568a48 92#ifdef STANDALONE_SOLVER
93#include <stdarg.h>
ab362080 94int solver_show_working, solver_recurse_depth;
7c568a48 95#endif
96
1d8e8ad8 97#include "puzzles.h"
98
99/*
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.
106 */
107typedef unsigned char digit;
108#define ORDER_MAX 255
109
1e3e152d 110#define PREFERRED_TILE_SIZE 32
111#define TILE_SIZE (ds->tilesize)
112#define BORDER (TILE_SIZE / 2)
1d8e8ad8 113
114#define FLASH_TIME 0.4F
115
154bf9b1 116enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
117 SYMM_REF4D, SYMM_REF8 };
ef57b17d 118
44bf5f6f 119enum { DIFF_BLOCK, DIFF_SIMPLE, DIFF_INTERSECT, DIFF_SET, DIFF_EXTREME,
13c4d60d 120 DIFF_RECURSIVE, DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
7c568a48 121
1d8e8ad8 122enum {
123 COL_BACKGROUND,
ef57b17d 124 COL_GRID,
125 COL_CLUE,
126 COL_USER,
127 COL_HIGHLIGHT,
7b14a9ec 128 COL_ERROR,
c8266e03 129 COL_PENCIL,
ef57b17d 130 NCOLOURS
1d8e8ad8 131};
132
133struct game_params {
7c568a48 134 int c, r, symm, diff;
1d8e8ad8 135};
136
137struct game_state {
138 int c, r;
139 digit *grid;
c8266e03 140 unsigned char *pencil; /* c*r*c*r elements */
1d8e8ad8 141 unsigned char *immutable; /* marks which digits are clues */
2ac6d24e 142 int completed, cheated;
1d8e8ad8 143};
144
145static game_params *default_params(void)
146{
147 game_params *ret = snew(game_params);
148
149 ret->c = ret->r = 3;
ef57b17d 150 ret->symm = SYMM_ROT2; /* a plausible default */
4f36adaa 151 ret->diff = DIFF_BLOCK; /* so is this */
1d8e8ad8 152
153 return ret;
154}
155
1d8e8ad8 156static void free_params(game_params *params)
157{
158 sfree(params);
159}
160
161static game_params *dup_params(game_params *params)
162{
163 game_params *ret = snew(game_params);
164 *ret = *params; /* structure copy */
165 return ret;
166}
167
7c568a48 168static int game_fetch_preset(int i, char **name, game_params **params)
169{
170 static struct {
171 char *title;
172 game_params params;
173 } presets[] = {
174 { "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK } },
175 { "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE } },
4f36adaa 176 { "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK } },
7c568a48 177 { "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE } },
178 { "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT } },
179 { "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET } },
44bf5f6f 180 { "3x3 Extreme", { 3, 3, SYMM_ROT2, DIFF_EXTREME } },
de60d8bd 181 { "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE } },
ab53eb64 182#ifndef SLOW_SYSTEM
7c568a48 183 { "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE } },
184 { "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE } },
ab53eb64 185#endif
7c568a48 186 };
187
188 if (i < 0 || i >= lenof(presets))
189 return FALSE;
190
191 *name = dupstr(presets[i].title);
192 *params = dup_params(&presets[i].params);
193
194 return TRUE;
195}
196
1185e3c5 197static void decode_params(game_params *ret, char const *string)
1d8e8ad8 198{
1d8e8ad8 199 ret->c = ret->r = atoi(string);
200 while (*string && isdigit((unsigned char)*string)) string++;
201 if (*string == 'x') {
202 string++;
203 ret->r = atoi(string);
204 while (*string && isdigit((unsigned char)*string)) string++;
205 }
7c568a48 206 while (*string) {
207 if (*string == 'r' || *string == 'm' || *string == 'a') {
154bf9b1 208 int sn, sc, sd;
7c568a48 209 sc = *string++;
28814d46 210 if (sc == 'm' && *string == 'd') {
154bf9b1 211 sd = TRUE;
212 string++;
213 } else {
214 sd = FALSE;
215 }
7c568a48 216 sn = atoi(string);
217 while (*string && isdigit((unsigned char)*string)) string++;
154bf9b1 218 if (sc == 'm' && sn == 8)
219 ret->symm = SYMM_REF8;
7c568a48 220 if (sc == 'm' && sn == 4)
154bf9b1 221 ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
222 if (sc == 'm' && sn == 2)
223 ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
7c568a48 224 if (sc == 'r' && sn == 4)
225 ret->symm = SYMM_ROT4;
226 if (sc == 'r' && sn == 2)
227 ret->symm = SYMM_ROT2;
228 if (sc == 'a')
229 ret->symm = SYMM_NONE;
230 } else if (*string == 'd') {
231 string++;
232 if (*string == 't') /* trivial */
233 string++, ret->diff = DIFF_BLOCK;
234 else if (*string == 'b') /* basic */
235 string++, ret->diff = DIFF_SIMPLE;
236 else if (*string == 'i') /* intermediate */
237 string++, ret->diff = DIFF_INTERSECT;
238 else if (*string == 'a') /* advanced */
239 string++, ret->diff = DIFF_SET;
13c4d60d 240 else if (*string == 'e') /* extreme */
44bf5f6f 241 string++, ret->diff = DIFF_EXTREME;
de60d8bd 242 else if (*string == 'u') /* unreasonable */
243 string++, ret->diff = DIFF_RECURSIVE;
7c568a48 244 } else
245 string++; /* eat unknown character */
ef57b17d 246 }
1d8e8ad8 247}
248
1185e3c5 249static char *encode_params(game_params *params, int full)
1d8e8ad8 250{
251 char str[80];
252
253 sprintf(str, "%dx%d", params->c, params->r);
1185e3c5 254 if (full) {
255 switch (params->symm) {
154bf9b1 256 case SYMM_REF8: strcat(str, "m8"); break;
1185e3c5 257 case SYMM_REF4: strcat(str, "m4"); break;
154bf9b1 258 case SYMM_REF4D: strcat(str, "md4"); break;
259 case SYMM_REF2: strcat(str, "m2"); break;
260 case SYMM_REF2D: strcat(str, "md2"); break;
1185e3c5 261 case SYMM_ROT4: strcat(str, "r4"); break;
262 /* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
263 case SYMM_NONE: strcat(str, "a"); break;
264 }
265 switch (params->diff) {
266 /* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
267 case DIFF_SIMPLE: strcat(str, "db"); break;
268 case DIFF_INTERSECT: strcat(str, "di"); break;
269 case DIFF_SET: strcat(str, "da"); break;
44bf5f6f 270 case DIFF_EXTREME: strcat(str, "de"); break;
1185e3c5 271 case DIFF_RECURSIVE: strcat(str, "du"); break;
272 }
273 }
1d8e8ad8 274 return dupstr(str);
275}
276
277static config_item *game_configure(game_params *params)
278{
279 config_item *ret;
280 char buf[80];
281
282 ret = snewn(5, config_item);
283
284 ret[0].name = "Columns of sub-blocks";
285 ret[0].type = C_STRING;
286 sprintf(buf, "%d", params->c);
287 ret[0].sval = dupstr(buf);
288 ret[0].ival = 0;
289
290 ret[1].name = "Rows of sub-blocks";
291 ret[1].type = C_STRING;
292 sprintf(buf, "%d", params->r);
293 ret[1].sval = dupstr(buf);
294 ret[1].ival = 0;
295
ef57b17d 296 ret[2].name = "Symmetry";
297 ret[2].type = C_CHOICES;
154bf9b1 298 ret[2].sval = ":None:2-way rotation:4-way rotation:2-way mirror:"
299 "2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
300 "8-way mirror";
ef57b17d 301 ret[2].ival = params->symm;
302
7c568a48 303 ret[3].name = "Difficulty";
304 ret[3].type = C_CHOICES;
13c4d60d 305 ret[3].sval = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
7c568a48 306 ret[3].ival = params->diff;
1d8e8ad8 307
7c568a48 308 ret[4].name = NULL;
309 ret[4].type = C_END;
310 ret[4].sval = NULL;
311 ret[4].ival = 0;
1d8e8ad8 312
313 return ret;
314}
315
316static game_params *custom_params(config_item *cfg)
317{
318 game_params *ret = snew(game_params);
319
c1f743c8 320 ret->c = atoi(cfg[0].sval);
321 ret->r = atoi(cfg[1].sval);
ef57b17d 322 ret->symm = cfg[2].ival;
7c568a48 323 ret->diff = cfg[3].ival;
1d8e8ad8 324
325 return ret;
326}
327
3ff276f2 328static char *validate_params(game_params *params, int full)
1d8e8ad8 329{
330 if (params->c < 2 || params->r < 2)
331 return "Both dimensions must be at least 2";
332 if (params->c > ORDER_MAX || params->r > ORDER_MAX)
333 return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
498eab1d 334 if ((params->c * params->r) > 35)
335 return "Unable to support more than 35 distinct symbols in a puzzle";
1d8e8ad8 336 return NULL;
337}
338
339/* ----------------------------------------------------------------------
ab362080 340 * Solver.
341 *
13c4d60d 342 * This solver is used for two purposes:
ab362080 343 * + to check solubility of a grid as we gradually remove numbers
344 * from it
345 * + to solve an externally generated puzzle when the user selects
346 * `Solve'.
347 *
1d8e8ad8 348 * It supports a variety of specific modes of reasoning. By
349 * enabling or disabling subsets of these modes we can arrange a
350 * range of difficulty levels.
351 */
352
353/*
354 * Modes of reasoning currently supported:
355 *
356 * - Positional elimination: a number must go in a particular
357 * square because all the other empty squares in a given
358 * row/col/blk are ruled out.
359 *
360 * - Numeric elimination: a square must have a particular number
361 * in because all the other numbers that could go in it are
362 * ruled out.
363 *
7c568a48 364 * - Intersectional analysis: given two domains which overlap
1d8e8ad8 365 * (hence one must be a block, and the other can be a row or
366 * col), if the possible locations for a particular number in
367 * one of the domains can be narrowed down to the overlap, then
368 * that number can be ruled out everywhere but the overlap in
369 * the other domain too.
370 *
7c568a48 371 * - Set elimination: if there is a subset of the empty squares
372 * within a domain such that the union of the possible numbers
373 * in that subset has the same size as the subset itself, then
374 * those numbers can be ruled out everywhere else in the domain.
375 * (For example, if there are five empty squares and the
376 * possible numbers in each are 12, 23, 13, 134 and 1345, then
377 * the first three empty squares form such a subset: the numbers
378 * 1, 2 and 3 _must_ be in those three squares in some
379 * permutation, and hence we can deduce none of them can be in
380 * the fourth or fifth squares.)
381 * + You can also see this the other way round, concentrating
382 * on numbers rather than squares: if there is a subset of
383 * the unplaced numbers within a domain such that the union
384 * of all their possible positions has the same size as the
385 * subset itself, then all other numbers can be ruled out for
386 * those positions. However, it turns out that this is
387 * exactly equivalent to the first formulation at all times:
388 * there is a 1-1 correspondence between suitable subsets of
389 * the unplaced numbers and suitable subsets of the unfilled
390 * places, found by taking the _complement_ of the union of
391 * the numbers' possible positions (or the spaces' possible
392 * contents).
ab362080 393 *
13c4d60d 394 * - Mutual neighbour elimination: find two squares A,B and a
395 * number N in the possible set of A, such that putting N in A
396 * would rule out enough possibilities from the mutual
397 * neighbours of A and B that there would be no possibilities
398 * left for B. Thereby rule out N in A.
399 * + The simplest case of this is if B has two possibilities
400 * (wlog {1,2}), and there are two mutual neighbours of A and
401 * B which have possibilities {1,3} and {2,3}. Thus, if A
402 * were to be 3, then those neighbours would contain 1 and 2,
403 * and hence there would be nothing left which could go in B.
404 * + There can be more complex cases of it too: if A and B are
405 * in the same column of large blocks, then they can have
406 * more than two mutual neighbours, some of which can also be
407 * neighbours of one another. Suppose, for example, that B
408 * has possibilities {1,2,3}; there's one square P in the
409 * same column as B and the same block as A, with
410 * possibilities {1,4}; and there are _two_ squares Q,R in
411 * the same column as A and the same block as B with
412 * possibilities {2,3,4}. Then if A contained 4, P would
413 * contain 1, and Q and R would have to contain 2 and 3 in
414 * _some_ order; therefore, once again, B would have no
415 * remaining possibilities.
416 *
ab362080 417 * - Recursion. If all else fails, we pick one of the currently
418 * most constrained empty squares and take a random guess at its
419 * contents, then continue solving on that basis and see if we
420 * get any further.
1d8e8ad8 421 */
422
4846f788 423/*
424 * Within this solver, I'm going to transform all y-coordinates by
425 * inverting the significance of the block number and the position
426 * within the block. That is, we will start with the top row of
427 * each block in order, then the second row of each block in order,
428 * etc.
429 *
430 * This transformation has the enormous advantage that it means
431 * every row, column _and_ block is described by an arithmetic
432 * progression of coordinates within the cubic array, so that I can
433 * use the same very simple function to do blockwise, row-wise and
434 * column-wise elimination.
435 */
436#define YTRANS(y) (((y)%c)*r+(y)/c)
437#define YUNTRANS(y) (((y)%r)*c+(y)/r)
438
ab362080 439struct solver_usage {
1d8e8ad8 440 int c, r, cr;
441 /*
442 * We set up a cubic array, indexed by x, y and digit; each
443 * element of this array is TRUE or FALSE according to whether
444 * or not that digit _could_ in principle go in that position.
445 *
446 * The way to index this array is cube[(x*cr+y)*cr+n-1].
4846f788 447 * y-coordinates in here are transformed.
1d8e8ad8 448 */
449 unsigned char *cube;
450 /*
451 * This is the grid in which we write down our final
4846f788 452 * deductions. y-coordinates in here are _not_ transformed.
1d8e8ad8 453 */
454 digit *grid;
455 /*
456 * Now we keep track, at a slightly higher level, of what we
457 * have yet to work out, to prevent doing the same deduction
458 * many times.
459 */
460 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
461 unsigned char *row;
462 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
463 unsigned char *col;
464 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
465 unsigned char *blk;
466};
4846f788 467#define cubepos(x,y,n) (((x)*usage->cr+(y))*usage->cr+(n)-1)
468#define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
1d8e8ad8 469
470/*
471 * Function called when we are certain that a particular square has
4846f788 472 * a particular number in it. The y-coordinate passed in here is
473 * transformed.
1d8e8ad8 474 */
ab362080 475static void solver_place(struct solver_usage *usage, int x, int y, int n)
1d8e8ad8 476{
477 int c = usage->c, r = usage->r, cr = usage->cr;
478 int i, j, bx, by;
479
480 assert(cube(x,y,n));
481
482 /*
483 * Rule out all other numbers in this square.
484 */
485 for (i = 1; i <= cr; i++)
486 if (i != n)
487 cube(x,y,i) = FALSE;
488
489 /*
490 * Rule out this number in all other positions in the row.
491 */
492 for (i = 0; i < cr; i++)
493 if (i != y)
494 cube(x,i,n) = FALSE;
495
496 /*
497 * Rule out this number in all other positions in the column.
498 */
499 for (i = 0; i < cr; i++)
500 if (i != x)
501 cube(i,y,n) = FALSE;
502
503 /*
504 * Rule out this number in all other positions in the block.
505 */
506 bx = (x/r)*r;
4846f788 507 by = y % r;
1d8e8ad8 508 for (i = 0; i < r; i++)
509 for (j = 0; j < c; j++)
4846f788 510 if (bx+i != x || by+j*r != y)
511 cube(bx+i,by+j*r,n) = FALSE;
1d8e8ad8 512
513 /*
514 * Enter the number in the result grid.
515 */
4846f788 516 usage->grid[YUNTRANS(y)*cr+x] = n;
1d8e8ad8 517
518 /*
519 * Cross out this number from the list of numbers left to place
520 * in its row, its column and its block.
521 */
522 usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
7c568a48 523 usage->blk[((y%r)*c+(x/r))*cr+n-1] = TRUE;
1d8e8ad8 524}
525
ab362080 526static int solver_elim(struct solver_usage *usage, int start, int step
7c568a48 527#ifdef STANDALONE_SOLVER
528 , char *fmt, ...
529#endif
530 )
1d8e8ad8 531{
4846f788 532 int c = usage->c, r = usage->r, cr = c*r;
533 int fpos, m, i;
1d8e8ad8 534
535 /*
4846f788 536 * Count the number of set bits within this section of the
537 * cube.
1d8e8ad8 538 */
539 m = 0;
4846f788 540 fpos = -1;
541 for (i = 0; i < cr; i++)
542 if (usage->cube[start+i*step]) {
543 fpos = start+i*step;
1d8e8ad8 544 m++;
545 }
546
547 if (m == 1) {
4846f788 548 int x, y, n;
549 assert(fpos >= 0);
1d8e8ad8 550
4846f788 551 n = 1 + fpos % cr;
552 y = fpos / cr;
553 x = y / cr;
554 y %= cr;
1d8e8ad8 555
3ddae0ff 556 if (!usage->grid[YUNTRANS(y)*cr+x]) {
7c568a48 557#ifdef STANDALONE_SOLVER
558 if (solver_show_working) {
559 va_list ap;
fdb3b29a 560 printf("%*s", solver_recurse_depth*4, "");
7c568a48 561 va_start(ap, fmt);
562 vprintf(fmt, ap);
563 va_end(ap);
ab362080 564 printf(":\n%*s placing %d at (%d,%d)\n",
565 solver_recurse_depth*4, "", n, 1+x, 1+YUNTRANS(y));
7c568a48 566 }
567#endif
ab362080 568 solver_place(usage, x, y, n);
569 return +1;
3ddae0ff 570 }
ab362080 571 } else if (m == 0) {
572#ifdef STANDALONE_SOLVER
573 if (solver_show_working) {
ab362080 574 va_list ap;
fdb3b29a 575 printf("%*s", solver_recurse_depth*4, "");
ab362080 576 va_start(ap, fmt);
577 vprintf(fmt, ap);
578 va_end(ap);
579 printf(":\n%*s no possibilities available\n",
580 solver_recurse_depth*4, "");
581 }
582#endif
583 return -1;
1d8e8ad8 584 }
585
ab362080 586 return 0;
1d8e8ad8 587}
588
ab362080 589static int solver_intersect(struct solver_usage *usage,
7c568a48 590 int start1, int step1, int start2, int step2
591#ifdef STANDALONE_SOLVER
592 , char *fmt, ...
593#endif
594 )
595{
596 int c = usage->c, r = usage->r, cr = c*r;
597 int ret, i;
598
599 /*
600 * Loop over the first domain and see if there's any set bit
601 * not also in the second.
602 */
603 for (i = 0; i < cr; i++) {
604 int p = start1+i*step1;
605 if (usage->cube[p] &&
606 !(p >= start2 && p < start2+cr*step2 &&
607 (p - start2) % step2 == 0))
ab362080 608 return 0; /* there is, so we can't deduce */
7c568a48 609 }
610
611 /*
612 * We have determined that all set bits in the first domain are
613 * within its overlap with the second. So loop over the second
614 * domain and remove all set bits that aren't also in that
ab362080 615 * overlap; return +1 iff we actually _did_ anything.
7c568a48 616 */
ab362080 617 ret = 0;
7c568a48 618 for (i = 0; i < cr; i++) {
619 int p = start2+i*step2;
620 if (usage->cube[p] &&
621 !(p >= start1 && p < start1+cr*step1 && (p - start1) % step1 == 0))
622 {
623#ifdef STANDALONE_SOLVER
624 if (solver_show_working) {
625 int px, py, pn;
626
627 if (!ret) {
628 va_list ap;
fdb3b29a 629 printf("%*s", solver_recurse_depth*4, "");
7c568a48 630 va_start(ap, fmt);
631 vprintf(fmt, ap);
632 va_end(ap);
633 printf(":\n");
634 }
635
636 pn = 1 + p % cr;
637 py = p / cr;
638 px = py / cr;
639 py %= cr;
640
ab362080 641 printf("%*s ruling out %d at (%d,%d)\n",
642 solver_recurse_depth*4, "", pn, 1+px, 1+YUNTRANS(py));
7c568a48 643 }
644#endif
ab362080 645 ret = +1; /* we did something */
7c568a48 646 usage->cube[p] = 0;
647 }
648 }
649
650 return ret;
651}
652
ab362080 653struct solver_scratch {
ab53eb64 654 unsigned char *grid, *rowidx, *colidx, *set;
44bf5f6f 655 int *neighbours, *bfsqueue;
656#ifdef STANDALONE_SOLVER
657 int *bfsprev;
658#endif
ab53eb64 659};
660
ab362080 661static int solver_set(struct solver_usage *usage,
662 struct solver_scratch *scratch,
7c568a48 663 int start, int step1, int step2
664#ifdef STANDALONE_SOLVER
665 , char *fmt, ...
666#endif
667 )
668{
669 int c = usage->c, r = usage->r, cr = c*r;
670 int i, j, n, count;
ab53eb64 671 unsigned char *grid = scratch->grid;
672 unsigned char *rowidx = scratch->rowidx;
673 unsigned char *colidx = scratch->colidx;
674 unsigned char *set = scratch->set;
7c568a48 675
676 /*
677 * We are passed a cr-by-cr matrix of booleans. Our first job
678 * is to winnow it by finding any definite placements - i.e.
679 * any row with a solitary 1 - and discarding that row and the
680 * column containing the 1.
681 */
682 memset(rowidx, TRUE, cr);
683 memset(colidx, TRUE, cr);
684 for (i = 0; i < cr; i++) {
685 int count = 0, first = -1;
686 for (j = 0; j < cr; j++)
687 if (usage->cube[start+i*step1+j*step2])
688 first = j, count++;
ab362080 689
690 /*
691 * If count == 0, then there's a row with no 1s at all and
692 * the puzzle is internally inconsistent. However, we ought
693 * to have caught this already during the simpler reasoning
694 * methods, so we can safely fail an assertion if we reach
695 * this point here.
696 */
697 assert(count > 0);
7c568a48 698 if (count == 1)
699 rowidx[i] = colidx[first] = FALSE;
700 }
701
702 /*
703 * Convert each of rowidx/colidx from a list of 0s and 1s to a
704 * list of the indices of the 1s.
705 */
706 for (i = j = 0; i < cr; i++)
707 if (rowidx[i])
708 rowidx[j++] = i;
709 n = j;
710 for (i = j = 0; i < cr; i++)
711 if (colidx[i])
712 colidx[j++] = i;
713 assert(n == j);
714
715 /*
716 * And create the smaller matrix.
717 */
718 for (i = 0; i < n; i++)
719 for (j = 0; j < n; j++)
720 grid[i*cr+j] = usage->cube[start+rowidx[i]*step1+colidx[j]*step2];
721
722 /*
723 * Having done that, we now have a matrix in which every row
724 * has at least two 1s in. Now we search to see if we can find
725 * a rectangle of zeroes (in the set-theoretic sense of
726 * `rectangle', i.e. a subset of rows crossed with a subset of
727 * columns) whose width and height add up to n.
728 */
729
730 memset(set, 0, n);
731 count = 0;
732 while (1) {
733 /*
734 * We have a candidate set. If its size is <=1 or >=n-1
735 * then we move on immediately.
736 */
737 if (count > 1 && count < n-1) {
738 /*
739 * The number of rows we need is n-count. See if we can
740 * find that many rows which each have a zero in all
741 * the positions listed in `set'.
742 */
743 int rows = 0;
744 for (i = 0; i < n; i++) {
745 int ok = TRUE;
746 for (j = 0; j < n; j++)
747 if (set[j] && grid[i*cr+j]) {
748 ok = FALSE;
749 break;
750 }
751 if (ok)
752 rows++;
753 }
754
755 /*
756 * We expect never to be able to get _more_ than
757 * n-count suitable rows: this would imply that (for
758 * example) there are four numbers which between them
759 * have at most three possible positions, and hence it
760 * indicates a faulty deduction before this point or
761 * even a bogus clue.
762 */
ab362080 763 if (rows > n - count) {
764#ifdef STANDALONE_SOLVER
765 if (solver_show_working) {
fdb3b29a 766 va_list ap;
ab362080 767 printf("%*s", solver_recurse_depth*4,
768 "");
ab362080 769 va_start(ap, fmt);
770 vprintf(fmt, ap);
771 va_end(ap);
772 printf(":\n%*s contradiction reached\n",
773 solver_recurse_depth*4, "");
774 }
775#endif
776 return -1;
777 }
778
7c568a48 779 if (rows >= n - count) {
780 int progress = FALSE;
781
782 /*
783 * We've got one! Now, for each row which _doesn't_
784 * satisfy the criterion, eliminate all its set
785 * bits in the positions _not_ listed in `set'.
ab362080 786 * Return +1 (meaning progress has been made) if we
787 * successfully eliminated anything at all.
7c568a48 788 *
789 * This involves referring back through
790 * rowidx/colidx in order to work out which actual
791 * positions in the cube to meddle with.
792 */
793 for (i = 0; i < n; i++) {
794 int ok = TRUE;
795 for (j = 0; j < n; j++)
796 if (set[j] && grid[i*cr+j]) {
797 ok = FALSE;
798 break;
799 }
800 if (!ok) {
801 for (j = 0; j < n; j++)
802 if (!set[j] && grid[i*cr+j]) {
803 int fpos = (start+rowidx[i]*step1+
804 colidx[j]*step2);
805#ifdef STANDALONE_SOLVER
806 if (solver_show_working) {
807 int px, py, pn;
ab362080 808
7c568a48 809 if (!progress) {
fdb3b29a 810 va_list ap;
ab362080 811 printf("%*s", solver_recurse_depth*4,
812 "");
7c568a48 813 va_start(ap, fmt);
814 vprintf(fmt, ap);
815 va_end(ap);
816 printf(":\n");
817 }
818
819 pn = 1 + fpos % cr;
820 py = fpos / cr;
821 px = py / cr;
822 py %= cr;
823
ab362080 824 printf("%*s ruling out %d at (%d,%d)\n",
825 solver_recurse_depth*4, "",
7c568a48 826 pn, 1+px, 1+YUNTRANS(py));
827 }
828#endif
829 progress = TRUE;
830 usage->cube[fpos] = FALSE;
831 }
832 }
833 }
834
835 if (progress) {
ab362080 836 return +1;
7c568a48 837 }
838 }
839 }
840
841 /*
842 * Binary increment: change the rightmost 0 to a 1, and
843 * change all 1s to the right of it to 0s.
844 */
845 i = n;
846 while (i > 0 && set[i-1])
847 set[--i] = 0, count--;
848 if (i > 0)
849 set[--i] = 1, count++;
850 else
851 break; /* done */
852 }
853
ab362080 854 return 0;
7c568a48 855}
856
13c4d60d 857/*
858 * Try to find a number in the possible set of (x1,y1) which can be
859 * ruled out because it would leave no possibilities for (x2,y2).
860 */
861static int solver_mne(struct solver_usage *usage,
862 struct solver_scratch *scratch,
863 int x1, int y1, int x2, int y2)
864{
865 int c = usage->c, r = usage->r, cr = c*r;
866 int *nb[2];
867 unsigned char *set = scratch->set;
868 unsigned char *numbers = scratch->rowidx;
869 unsigned char *numbersleft = scratch->colidx;
870 int nnb, count;
871 int i, j, n, nbi;
872
44bf5f6f 873 nb[0] = scratch->neighbours;
874 nb[1] = scratch->neighbours + cr;
13c4d60d 875
876 /*
877 * First, work out the mutual neighbour squares of the two. We
878 * can assert that they're not actually in the same block,
879 * which leaves two possibilities: they're in different block
880 * rows _and_ different block columns (thus their mutual
881 * neighbours are precisely the other two corners of the
882 * rectangle), or they're in the same row (WLOG) and different
883 * columns, in which case their mutual neighbours are the
884 * column of each block aligned with the other square.
885 *
886 * We divide the mutual neighbours into two separate subsets
887 * nb[0] and nb[1]; squares in the same subset are not only
888 * adjacent to both our key squares, but are also always
889 * adjacent to one another.
890 */
891 if (x1 / r != x2 / r && y1 % r != y2 % r) {
892 /* Corners of the rectangle. */
893 nnb = 1;
894 nb[0][0] = cubepos(x2, y1, 1);
895 nb[1][0] = cubepos(x1, y2, 1);
896 } else if (x1 / r != x2 / r) {
897 /* Same row of blocks; different blocks within that row. */
898 int x1b = x1 - (x1 % r);
899 int x2b = x2 - (x2 % r);
900
901 nnb = r;
902 for (i = 0; i < r; i++) {
903 nb[0][i] = cubepos(x2b+i, y1, 1);
904 nb[1][i] = cubepos(x1b+i, y2, 1);
905 }
906 } else {
907 /* Same column of blocks; different blocks within that column. */
908 int y1b = y1 % r;
909 int y2b = y2 % r;
910
911 assert(y1 % r != y2 % r);
912
913 nnb = c;
914 for (i = 0; i < c; i++) {
915 nb[0][i] = cubepos(x2, y1b+i*r, 1);
916 nb[1][i] = cubepos(x1, y2b+i*r, 1);
917 }
918 }
919
920 /*
921 * Right. Now loop over each possible number.
922 */
923 for (n = 1; n <= cr; n++) {
924 if (!cube(x1, y1, n))
925 continue;
926 for (j = 0; j < cr; j++)
927 numbersleft[j] = cube(x2, y2, j+1);
928
929 /*
930 * Go over every possible subset of each neighbour list,
931 * and see if its union of possible numbers minus n has the
932 * same size as the subset. If so, add the numbers in that
933 * subset to the set of things which would be ruled out
934 * from (x2,y2) if n were placed at (x1,y1).
935 */
936 memset(set, 0, nnb);
937 count = 0;
938 while (1) {
939 /*
940 * Binary increment: change the rightmost 0 to a 1, and
941 * change all 1s to the right of it to 0s.
942 */
943 i = nnb;
944 while (i > 0 && set[i-1])
945 set[--i] = 0, count--;
946 if (i > 0)
947 set[--i] = 1, count++;
948 else
949 break; /* done */
950
951 /*
952 * Examine this subset of each neighbour set.
953 */
954 for (nbi = 0; nbi < 2; nbi++) {
955 int *nbs = nb[nbi];
956
957 memset(numbers, 0, cr);
958
959 for (i = 0; i < nnb; i++)
960 if (set[i])
961 for (j = 0; j < cr; j++)
962 if (j != n-1 && usage->cube[nbs[i] + j])
963 numbers[j] = 1;
964
965 for (i = j = 0; j < cr; j++)
966 i += numbers[j];
967
968 if (i == count) {
969 /*
970 * Got one. This subset of nbs, in the absence
971 * of n, would definitely contain all the
972 * numbers listed in `numbers'. Rule them out
973 * of `numbersleft'.
974 */
975 for (j = 0; j < cr; j++)
976 if (numbers[j])
977 numbersleft[j] = 0;
978 }
979 }
980 }
981
982 /*
983 * If we've got nothing left in `numbersleft', we have a
984 * successful mutual neighbour elimination.
985 */
986 for (j = 0; j < cr; j++)
987 if (numbersleft[j])
988 break;
989
990 if (j == cr) {
991#ifdef STANDALONE_SOLVER
992 if (solver_show_working) {
993 printf("%*smutual neighbour elimination, (%d,%d) vs (%d,%d):\n",
994 solver_recurse_depth*4, "",
995 1+x1, 1+YUNTRANS(y1), 1+x2, 1+YUNTRANS(y2));
996 printf("%*s ruling out %d at (%d,%d)\n",
997 solver_recurse_depth*4, "",
998 n, 1+x1, 1+YUNTRANS(y1));
999 }
1000#endif
1001 cube(x1, y1, n) = FALSE;
1002 return +1;
1003 }
1004 }
1005
1006 return 0; /* nothing found */
1007}
1008
44bf5f6f 1009/*
1010 * Look for forcing chains. A forcing chain is a path of
1011 * pairwise-exclusive squares (i.e. each pair of adjacent squares
1012 * in the path are in the same row, column or block) with the
1013 * following properties:
1014 *
1015 * (a) Each square on the path has precisely two possible numbers.
1016 *
1017 * (b) Each pair of squares which are adjacent on the path share
1018 * at least one possible number in common.
1019 *
1020 * (c) Each square in the middle of the path shares _both_ of its
1021 * numbers with at least one of its neighbours (not the same
1022 * one with both neighbours).
1023 *
1024 * These together imply that at least one of the possible number
1025 * choices at one end of the path forces _all_ the rest of the
1026 * numbers along the path. In order to make real use of this, we
1027 * need further properties:
1028 *
1029 * (c) Ruling out some number N from the square at one end
1030 * of the path forces the square at the other end to
1031 * take number N.
1032 *
1033 * (d) The two end squares are both in line with some third
1034 * square.
1035 *
1036 * (e) That third square currently has N as a possibility.
1037 *
1038 * If we can find all of that lot, we can deduce that at least one
1039 * of the two ends of the forcing chain has number N, and that
1040 * therefore the mutually adjacent third square does not.
1041 *
1042 * To find forcing chains, we're going to start a bfs at each
1043 * suitable square, once for each of its two possible numbers.
1044 */
1045static int solver_forcing(struct solver_usage *usage,
1046 struct solver_scratch *scratch)
1047{
1048 int c = usage->c, r = usage->r, cr = c*r;
1049 int *bfsqueue = scratch->bfsqueue;
1050#ifdef STANDALONE_SOLVER
1051 int *bfsprev = scratch->bfsprev;
1052#endif
1053 unsigned char *number = scratch->grid;
1054 int *neighbours = scratch->neighbours;
1055 int x, y;
1056
1057 for (y = 0; y < cr; y++)
1058 for (x = 0; x < cr; x++) {
1059 int count, t, n;
1060
1061 /*
1062 * If this square doesn't have exactly two candidate
1063 * numbers, don't try it.
1064 *
1065 * In this loop we also sum the candidate numbers,
1066 * which is a nasty hack to allow us to quickly find
1067 * `the other one' (since we will shortly know there
1068 * are exactly two).
1069 */
1070 for (count = t = 0, n = 1; n <= cr; n++)
1071 if (cube(x, y, n))
1072 count++, t += n;
1073 if (count != 2)
1074 continue;
1075
1076 /*
1077 * Now attempt a bfs for each candidate.
1078 */
1079 for (n = 1; n <= cr; n++)
1080 if (cube(x, y, n)) {
1081 int orign, currn, head, tail;
1082
1083 /*
1084 * Begin a bfs.
1085 */
1086 orign = n;
1087
1088 memset(number, cr+1, cr*cr);
1089 head = tail = 0;
1090 bfsqueue[tail++] = y*cr+x;
1091#ifdef STANDALONE_SOLVER
1092 bfsprev[y*cr+x] = -1;
1093#endif
1094 number[y*cr+x] = t - n;
1095
1096 while (head < tail) {
1097 int xx, yy, nneighbours, xt, yt, xblk, i;
1098
1099 xx = bfsqueue[head++];
1100 yy = xx / cr;
1101 xx %= cr;
1102
1103 currn = number[yy*cr+xx];
1104
1105 /*
1106 * Find neighbours of yy,xx.
1107 */
1108 nneighbours = 0;
1109 for (yt = 0; yt < cr; yt++)
1110 neighbours[nneighbours++] = yt*cr+xx;
1111 for (xt = 0; xt < cr; xt++)
1112 neighbours[nneighbours++] = yy*cr+xt;
1113 xblk = xx - (xx % r);
1114 for (yt = yy % r; yt < cr; yt += r)
1115 for (xt = xblk; xt < xblk+r; xt++)
1116 neighbours[nneighbours++] = yt*cr+xt;
1117
1118 /*
1119 * Try visiting each of those neighbours.
1120 */
1121 for (i = 0; i < nneighbours; i++) {
1122 int cc, tt, nn;
1123
1124 xt = neighbours[i] % cr;
1125 yt = neighbours[i] / cr;
1126
1127 /*
1128 * We need this square to not be
1129 * already visited, and to include
1130 * currn as a possible number.
1131 */
1132 if (number[yt*cr+xt] <= cr)
1133 continue;
1134 if (!cube(xt, yt, currn))
1135 continue;
1136
1137 /*
1138 * Don't visit _this_ square a second
1139 * time!
1140 */
1141 if (xt == xx && yt == yy)
1142 continue;
1143
1144 /*
1145 * To continue with the bfs, we need
1146 * this square to have exactly two
1147 * possible numbers.
1148 */
1149 for (cc = tt = 0, nn = 1; nn <= cr; nn++)
1150 if (cube(xt, yt, nn))
1151 cc++, tt += nn;
1152 if (cc == 2) {
1153 bfsqueue[tail++] = yt*cr+xt;
1154#ifdef STANDALONE_SOLVER
1155 bfsprev[yt*cr+xt] = yy*cr+xx;
1156#endif
1157 number[yt*cr+xt] = tt - currn;
1158 }
1159
1160 /*
1161 * One other possibility is that this
1162 * might be the square in which we can
1163 * make a real deduction: if it's
1164 * adjacent to x,y, and currn is equal
1165 * to the original number we ruled out.
1166 */
1167 if (currn == orign &&
1168 (xt == x || yt == y ||
1169 (xt / r == x / r && yt % r == y % r))) {
1170#ifdef STANDALONE_SOLVER
1171 if (solver_show_working) {
1172 char *sep = "";
1173 int xl, yl;
1174 printf("%*sforcing chain, %d at ends of ",
1175 solver_recurse_depth*4, "", orign);
1176 xl = xx;
1177 yl = yy;
1178 while (1) {
1179 printf("%s(%d,%d)", sep, 1+xl,
1180 1+YUNTRANS(yl));
1181 xl = bfsprev[yl*cr+xl];
1182 if (xl < 0)
1183 break;
1184 yl = xl / cr;
1185 xl %= cr;
1186 sep = "-";
1187 }
1188 printf("\n%*s ruling out %d at (%d,%d)\n",
1189 solver_recurse_depth*4, "",
1190 orign, 1+xt, 1+YUNTRANS(yt));
1191 }
1192#endif
1193 cube(xt, yt, orign) = FALSE;
1194 return 1;
1195 }
1196 }
1197 }
1198 }
1199 }
1200
1201 return 0;
1202}
1203
ab362080 1204static struct solver_scratch *solver_new_scratch(struct solver_usage *usage)
ab53eb64 1205{
ab362080 1206 struct solver_scratch *scratch = snew(struct solver_scratch);
ab53eb64 1207 int cr = usage->cr;
1208 scratch->grid = snewn(cr*cr, unsigned char);
1209 scratch->rowidx = snewn(cr, unsigned char);
1210 scratch->colidx = snewn(cr, unsigned char);
1211 scratch->set = snewn(cr, unsigned char);
44bf5f6f 1212 scratch->neighbours = snewn(3*cr, int);
1213 scratch->bfsqueue = snewn(cr*cr, int);
1214#ifdef STANDALONE_SOLVER
1215 scratch->bfsprev = snewn(cr*cr, int);
1216#endif
ab53eb64 1217 return scratch;
1218}
1219
ab362080 1220static void solver_free_scratch(struct solver_scratch *scratch)
ab53eb64 1221{
44bf5f6f 1222#ifdef STANDALONE_SOLVER
1223 sfree(scratch->bfsprev);
1224#endif
1225 sfree(scratch->bfsqueue);
1226 sfree(scratch->neighbours);
ab53eb64 1227 sfree(scratch->set);
1228 sfree(scratch->colidx);
1229 sfree(scratch->rowidx);
1230 sfree(scratch->grid);
1231 sfree(scratch);
1232}
1233
947a07d6 1234static int solver(int c, int r, digit *grid, int maxdiff)
1d8e8ad8 1235{
ab362080 1236 struct solver_usage *usage;
1237 struct solver_scratch *scratch;
1d8e8ad8 1238 int cr = c*r;
13c4d60d 1239 int x, y, x2, y2, n, ret;
7c568a48 1240 int diff = DIFF_BLOCK;
1d8e8ad8 1241
1242 /*
1243 * Set up a usage structure as a clean slate (everything
1244 * possible).
1245 */
ab362080 1246 usage = snew(struct solver_usage);
1d8e8ad8 1247 usage->c = c;
1248 usage->r = r;
1249 usage->cr = cr;
1250 usage->cube = snewn(cr*cr*cr, unsigned char);
1251 usage->grid = grid; /* write straight back to the input */
1252 memset(usage->cube, TRUE, cr*cr*cr);
1253
1254 usage->row = snewn(cr * cr, unsigned char);
1255 usage->col = snewn(cr * cr, unsigned char);
1256 usage->blk = snewn(cr * cr, unsigned char);
1257 memset(usage->row, FALSE, cr * cr);
1258 memset(usage->col, FALSE, cr * cr);
1259 memset(usage->blk, FALSE, cr * cr);
1260
ab362080 1261 scratch = solver_new_scratch(usage);
ab53eb64 1262
1d8e8ad8 1263 /*
1264 * Place all the clue numbers we are given.
1265 */
1266 for (x = 0; x < cr; x++)
1267 for (y = 0; y < cr; y++)
1268 if (grid[y*cr+x])
ab362080 1269 solver_place(usage, x, YTRANS(y), grid[y*cr+x]);
1d8e8ad8 1270
1271 /*
1272 * Now loop over the grid repeatedly trying all permitted modes
1273 * of reasoning. The loop terminates if we complete an
1274 * iteration without making any progress; we then return
1275 * failure or success depending on whether the grid is full or
1276 * not.
1277 */
1278 while (1) {
7c568a48 1279 /*
1280 * I'd like to write `continue;' inside each of the
1281 * following loops, so that the solver returns here after
1282 * making some progress. However, I can't specify that I
1283 * want to continue an outer loop rather than the innermost
1284 * one, so I'm apologetically resorting to a goto.
1285 */
3ddae0ff 1286 cont:
1287
1d8e8ad8 1288 /*
1289 * Blockwise positional elimination.
1290 */
4846f788 1291 for (x = 0; x < cr; x += r)
1d8e8ad8 1292 for (y = 0; y < r; y++)
1293 for (n = 1; n <= cr; n++)
ab362080 1294 if (!usage->blk[(y*c+(x/r))*cr+n-1]) {
1295 ret = solver_elim(usage, cubepos(x,y,n), r*cr
7c568a48 1296#ifdef STANDALONE_SOLVER
ab362080 1297 , "positional elimination,"
1298 " %d in block (%d,%d)", n, 1+x/r, 1+y
7c568a48 1299#endif
ab362080 1300 );
1301 if (ret < 0) {
1302 diff = DIFF_IMPOSSIBLE;
1303 goto got_result;
1304 } else if (ret > 0) {
1305 diff = max(diff, DIFF_BLOCK);
1306 goto cont;
1307 }
7c568a48 1308 }
1d8e8ad8 1309
ab362080 1310 if (maxdiff <= DIFF_BLOCK)
1311 break;
1312
1d8e8ad8 1313 /*
1314 * Row-wise positional elimination.
1315 */
1316 for (y = 0; y < cr; y++)
1317 for (n = 1; n <= cr; n++)
ab362080 1318 if (!usage->row[y*cr+n-1]) {
1319 ret = solver_elim(usage, cubepos(0,y,n), cr*cr
7c568a48 1320#ifdef STANDALONE_SOLVER
ab362080 1321 , "positional elimination,"
1322 " %d in row %d", n, 1+YUNTRANS(y)
7c568a48 1323#endif
ab362080 1324 );
1325 if (ret < 0) {
1326 diff = DIFF_IMPOSSIBLE;
1327 goto got_result;
1328 } else if (ret > 0) {
1329 diff = max(diff, DIFF_SIMPLE);
1330 goto cont;
1331 }
7c568a48 1332 }
1d8e8ad8 1333 /*
1334 * Column-wise positional elimination.
1335 */
1336 for (x = 0; x < cr; x++)
1337 for (n = 1; n <= cr; n++)
ab362080 1338 if (!usage->col[x*cr+n-1]) {
1339 ret = solver_elim(usage, cubepos(x,0,n), cr
7c568a48 1340#ifdef STANDALONE_SOLVER
ab362080 1341 , "positional elimination,"
1342 " %d in column %d", n, 1+x
7c568a48 1343#endif
ab362080 1344 );
1345 if (ret < 0) {
1346 diff = DIFF_IMPOSSIBLE;
1347 goto got_result;
1348 } else if (ret > 0) {
1349 diff = max(diff, DIFF_SIMPLE);
1350 goto cont;
1351 }
7c568a48 1352 }
1d8e8ad8 1353
1354 /*
1355 * Numeric elimination.
1356 */
1357 for (x = 0; x < cr; x++)
1358 for (y = 0; y < cr; y++)
ab362080 1359 if (!usage->grid[YUNTRANS(y)*cr+x]) {
1360 ret = solver_elim(usage, cubepos(x,y,1), 1
7c568a48 1361#ifdef STANDALONE_SOLVER
ab362080 1362 , "numeric elimination at (%d,%d)", 1+x,
1363 1+YUNTRANS(y)
7c568a48 1364#endif
ab362080 1365 );
1366 if (ret < 0) {
1367 diff = DIFF_IMPOSSIBLE;
1368 goto got_result;
1369 } else if (ret > 0) {
1370 diff = max(diff, DIFF_SIMPLE);
1371 goto cont;
1372 }
7c568a48 1373 }
1374
ab362080 1375 if (maxdiff <= DIFF_SIMPLE)
1376 break;
1377
7c568a48 1378 /*
1379 * Intersectional analysis, rows vs blocks.
1380 */
1381 for (y = 0; y < cr; y++)
1382 for (x = 0; x < cr; x += r)
1383 for (n = 1; n <= cr; n++)
ab362080 1384 /*
1385 * solver_intersect() never returns -1.
1386 */
7c568a48 1387 if (!usage->row[y*cr+n-1] &&
1388 !usage->blk[((y%r)*c+(x/r))*cr+n-1] &&
ab362080 1389 (solver_intersect(usage, cubepos(0,y,n), cr*cr,
7c568a48 1390 cubepos(x,y%r,n), r*cr
1391#ifdef STANDALONE_SOLVER
1392 , "intersectional analysis,"
ab362080 1393 " %d in row %d vs block (%d,%d)",
1394 n, 1+YUNTRANS(y), 1+x/r, 1+y%r
7c568a48 1395#endif
1396 ) ||
ab362080 1397 solver_intersect(usage, cubepos(x,y%r,n), r*cr,
7c568a48 1398 cubepos(0,y,n), cr*cr
1399#ifdef STANDALONE_SOLVER
1400 , "intersectional analysis,"
ab362080 1401 " %d in block (%d,%d) vs row %d",
1402 n, 1+x/r, 1+y%r, 1+YUNTRANS(y)
7c568a48 1403#endif
1404 ))) {
1405 diff = max(diff, DIFF_INTERSECT);
1406 goto cont;
1407 }
1408
1409 /*
1410 * Intersectional analysis, columns vs blocks.
1411 */
1412 for (x = 0; x < cr; x++)
1413 for (y = 0; y < r; y++)
1414 for (n = 1; n <= cr; n++)
1415 if (!usage->col[x*cr+n-1] &&
1416 !usage->blk[(y*c+(x/r))*cr+n-1] &&
ab362080 1417 (solver_intersect(usage, cubepos(x,0,n), cr,
7c568a48 1418 cubepos((x/r)*r,y,n), r*cr
1419#ifdef STANDALONE_SOLVER
1420 , "intersectional analysis,"
ab362080 1421 " %d in column %d vs block (%d,%d)",
1422 n, 1+x, 1+x/r, 1+y
7c568a48 1423#endif
1424 ) ||
ab362080 1425 solver_intersect(usage, cubepos((x/r)*r,y,n), r*cr,
7c568a48 1426 cubepos(x,0,n), cr
1427#ifdef STANDALONE_SOLVER
1428 , "intersectional analysis,"
ab362080 1429 " %d in block (%d,%d) vs column %d",
1430 n, 1+x/r, 1+y, 1+x
7c568a48 1431#endif
1432 ))) {
1433 diff = max(diff, DIFF_INTERSECT);
1434 goto cont;
1435 }
1436
ab362080 1437 if (maxdiff <= DIFF_INTERSECT)
1438 break;
1439
7c568a48 1440 /*
1441 * Blockwise set elimination.
1442 */
1443 for (x = 0; x < cr; x += r)
ab362080 1444 for (y = 0; y < r; y++) {
1445 ret = solver_set(usage, scratch, cubepos(x,y,1), r*cr, 1
7c568a48 1446#ifdef STANDALONE_SOLVER
ab362080 1447 , "set elimination, block (%d,%d)", 1+x/r, 1+y
7c568a48 1448#endif
ab362080 1449 );
1450 if (ret < 0) {
1451 diff = DIFF_IMPOSSIBLE;
1452 goto got_result;
1453 } else if (ret > 0) {
1454 diff = max(diff, DIFF_SET);
1455 goto cont;
1456 }
1457 }
7c568a48 1458
1459 /*
1460 * Row-wise set elimination.
1461 */
ab362080 1462 for (y = 0; y < cr; y++) {
1463 ret = solver_set(usage, scratch, cubepos(0,y,1), cr*cr, 1
7c568a48 1464#ifdef STANDALONE_SOLVER
ab362080 1465 , "set elimination, row %d", 1+YUNTRANS(y)
7c568a48 1466#endif
ab362080 1467 );
1468 if (ret < 0) {
1469 diff = DIFF_IMPOSSIBLE;
1470 goto got_result;
1471 } else if (ret > 0) {
1472 diff = max(diff, DIFF_SET);
1473 goto cont;
1474 }
1475 }
7c568a48 1476
1477 /*
1478 * Column-wise set elimination.
1479 */
ab362080 1480 for (x = 0; x < cr; x++) {
1481 ret = solver_set(usage, scratch, cubepos(x,0,1), cr, 1
7c568a48 1482#ifdef STANDALONE_SOLVER
ab362080 1483 , "set elimination, column %d", 1+x
7c568a48 1484#endif
ab362080 1485 );
1486 if (ret < 0) {
1487 diff = DIFF_IMPOSSIBLE;
1488 goto got_result;
1489 } else if (ret > 0) {
1490 diff = max(diff, DIFF_SET);
1491 goto cont;
1492 }
1493 }
1d8e8ad8 1494
1495 /*
44bf5f6f 1496 * Row-vs-column set elimination on a single number.
1497 */
1498 for (n = 1; n <= cr; n++) {
1499 ret = solver_set(usage, scratch, cubepos(0,0,n), cr*cr, cr
1500#ifdef STANDALONE_SOLVER
1501 , "positional set elimination, number %d", n
1502#endif
1503 );
1504 if (ret < 0) {
1505 diff = DIFF_IMPOSSIBLE;
1506 goto got_result;
1507 } else if (ret > 0) {
1508 diff = max(diff, DIFF_EXTREME);
1509 goto cont;
1510 }
1511 }
1512
1513 /*
13c4d60d 1514 * Mutual neighbour elimination.
1515 */
1516 for (y = 0; y+1 < cr; y++) {
1517 for (x = 0; x+1 < cr; x++) {
1518 for (y2 = y+1; y2 < cr; y2++) {
1519 for (x2 = x+1; x2 < cr; x2++) {
1520 /*
1521 * Can't do mutual neighbour elimination
1522 * between elements of the same actual
1523 * block.
1524 */
1525 if (x/r == x2/r && y%r == y2%r)
1526 continue;
1527
1528 /*
1529 * Otherwise, try (x,y) vs (x2,y2) in both
1530 * directions, and likewise (x2,y) vs
1531 * (x,y2).
1532 */
1533 if (!usage->grid[YUNTRANS(y)*cr+x] &&
1534 !usage->grid[YUNTRANS(y2)*cr+x2] &&
1535 (solver_mne(usage, scratch, x, y, x2, y2) ||
1536 solver_mne(usage, scratch, x2, y2, x, y))) {
44bf5f6f 1537 diff = max(diff, DIFF_EXTREME);
13c4d60d 1538 goto cont;
1539 }
1540 if (!usage->grid[YUNTRANS(y)*cr+x2] &&
1541 !usage->grid[YUNTRANS(y2)*cr+x] &&
1542 (solver_mne(usage, scratch, x2, y, x, y2) ||
1543 solver_mne(usage, scratch, x, y2, x2, y))) {
44bf5f6f 1544 diff = max(diff, DIFF_EXTREME);
13c4d60d 1545 goto cont;
1546 }
1547 }
1548 }
1549 }
1550 }
1551
44bf5f6f 1552 /*
1553 * Forcing chains.
1554 */
1555 if (solver_forcing(usage, scratch)) {
1556 diff = max(diff, DIFF_EXTREME);
1557 goto cont;
1558 }
1559
13c4d60d 1560 /*
1d8e8ad8 1561 * If we reach here, we have made no deductions in this
1562 * iteration, so the algorithm terminates.
1563 */
1564 break;
1565 }
1566
ab362080 1567 /*
1568 * Last chance: if we haven't fully solved the puzzle yet, try
1569 * recursing based on guesses for a particular square. We pick
1570 * one of the most constrained empty squares we can find, which
1571 * has the effect of pruning the search tree as much as
1572 * possible.
1573 */
1574 if (maxdiff >= DIFF_RECURSIVE) {
947a07d6 1575 int best, bestcount;
ab362080 1576
1577 best = -1;
1578 bestcount = cr+1;
ab362080 1579
1580 for (y = 0; y < cr; y++)
1581 for (x = 0; x < cr; x++)
1582 if (!grid[y*cr+x]) {
1583 int count;
1584
1585 /*
1586 * An unfilled square. Count the number of
1587 * possible digits in it.
1588 */
1589 count = 0;
1590 for (n = 1; n <= cr; n++)
1591 if (cube(x,YTRANS(y),n))
1592 count++;
1593
1594 /*
1595 * We should have found any impossibilities
1596 * already, so this can safely be an assert.
1597 */
1598 assert(count > 1);
1599
1600 if (count < bestcount) {
1601 bestcount = count;
947a07d6 1602 best = y*cr+x;
ab362080 1603 }
1604 }
1605
1606 if (best != -1) {
1607 int i, j;
1608 digit *list, *ingrid, *outgrid;
1609
1610 diff = DIFF_IMPOSSIBLE; /* no solution found yet */
1611
1612 /*
1613 * Attempt recursion.
1614 */
1615 y = best / cr;
1616 x = best % cr;
1617
1618 list = snewn(cr, digit);
1619 ingrid = snewn(cr * cr, digit);
1620 outgrid = snewn(cr * cr, digit);
1621 memcpy(ingrid, grid, cr * cr);
1622
1623 /* Make a list of the possible digits. */
1624 for (j = 0, n = 1; n <= cr; n++)
1625 if (cube(x,YTRANS(y),n))
1626 list[j++] = n;
1627
1628#ifdef STANDALONE_SOLVER
1629 if (solver_show_working) {
1630 char *sep = "";
1631 printf("%*srecursing on (%d,%d) [",
49d4feb5 1632 solver_recurse_depth*4, "", x + 1, y + 1);
ab362080 1633 for (i = 0; i < j; i++) {
1634 printf("%s%d", sep, list[i]);
1635 sep = " or ";
1636 }
1637 printf("]\n");
1638 }
1639#endif
1640
ab362080 1641 /*
1642 * And step along the list, recursing back into the
1643 * main solver at every stage.
1644 */
1645 for (i = 0; i < j; i++) {
1646 int ret;
1647
1648 memcpy(outgrid, ingrid, cr * cr);
1649 outgrid[y*cr+x] = list[i];
1650
1651#ifdef STANDALONE_SOLVER
1652 if (solver_show_working)
1653 printf("%*sguessing %d at (%d,%d)\n",
49d4feb5 1654 solver_recurse_depth*4, "", list[i], x + 1, y + 1);
ab362080 1655 solver_recurse_depth++;
1656#endif
1657
947a07d6 1658 ret = solver(c, r, outgrid, maxdiff);
ab362080 1659
1660#ifdef STANDALONE_SOLVER
1661 solver_recurse_depth--;
1662 if (solver_show_working) {
1663 printf("%*sretracting %d at (%d,%d)\n",
49d4feb5 1664 solver_recurse_depth*4, "", list[i], x + 1, y + 1);
ab362080 1665 }
1666#endif
1667
1668 /*
1669 * If we have our first solution, copy it into the
1670 * grid we will return.
1671 */
1672 if (diff == DIFF_IMPOSSIBLE && ret != DIFF_IMPOSSIBLE)
1673 memcpy(grid, outgrid, cr*cr);
1674
1675 if (ret == DIFF_AMBIGUOUS)
1676 diff = DIFF_AMBIGUOUS;
1677 else if (ret == DIFF_IMPOSSIBLE)
1678 /* do not change our return value */;
1679 else {
1680 /* the recursion turned up exactly one solution */
1681 if (diff == DIFF_IMPOSSIBLE)
1682 diff = DIFF_RECURSIVE;
1683 else
1684 diff = DIFF_AMBIGUOUS;
1685 }
1686
1687 /*
1688 * As soon as we've found more than one solution,
1689 * give up immediately.
1690 */
1691 if (diff == DIFF_AMBIGUOUS)
1692 break;
1693 }
1694
1695 sfree(outgrid);
1696 sfree(ingrid);
1697 sfree(list);
1698 }
1699
1700 } else {
1701 /*
1702 * We're forbidden to use recursion, so we just see whether
1703 * our grid is fully solved, and return DIFF_IMPOSSIBLE
1704 * otherwise.
1705 */
1706 for (y = 0; y < cr; y++)
1707 for (x = 0; x < cr; x++)
1708 if (!grid[y*cr+x])
1709 diff = DIFF_IMPOSSIBLE;
1710 }
1711
1712 got_result:;
1713
1714#ifdef STANDALONE_SOLVER
1715 if (solver_show_working)
1716 printf("%*s%s found\n",
1717 solver_recurse_depth*4, "",
1718 diff == DIFF_IMPOSSIBLE ? "no solution" :
1719 diff == DIFF_AMBIGUOUS ? "multiple solutions" :
1720 "one solution");
1721#endif
ab53eb64 1722
1d8e8ad8 1723 sfree(usage->cube);
1724 sfree(usage->row);
1725 sfree(usage->col);
1726 sfree(usage->blk);
1727 sfree(usage);
1728
ab362080 1729 solver_free_scratch(scratch);
1730
7c568a48 1731 return diff;
1d8e8ad8 1732}
1733
1734/* ----------------------------------------------------------------------
ab362080 1735 * End of solver code.
1736 */
1737
1738/* ----------------------------------------------------------------------
1739 * Solo filled-grid generator.
1740 *
1741 * This grid generator works by essentially trying to solve a grid
1742 * starting from no clues, and not worrying that there's more than
1743 * one possible solution. Unfortunately, it isn't computationally
1744 * feasible to do this by calling the above solver with an empty
1745 * grid, because that one needs to allocate a lot of scratch space
1746 * at every recursion level. Instead, I have a much simpler
1747 * algorithm which I shamelessly copied from a Python solver
1748 * written by Andrew Wilkinson (which is GPLed, but I've reused
1749 * only ideas and no code). It mostly just does the obvious
1750 * recursive thing: pick an empty square, put one of the possible
1751 * digits in it, recurse until all squares are filled, backtrack
1752 * and change some choices if necessary.
1753 *
1754 * The clever bit is that every time it chooses which square to
1755 * fill in next, it does so by counting the number of _possible_
1756 * numbers that can go in each square, and it prioritises so that
1757 * it picks a square with the _lowest_ number of possibilities. The
1758 * idea is that filling in lots of the obvious bits (particularly
1759 * any squares with only one possibility) will cut down on the list
1760 * of possibilities for other squares and hence reduce the enormous
1761 * search space as much as possible as early as possible.
1762 */
1763
1764/*
1765 * Internal data structure used in gridgen to keep track of
1766 * progress.
1767 */
1768struct gridgen_coord { int x, y, r; };
1769struct gridgen_usage {
1770 int c, r, cr; /* cr == c*r */
1771 /* grid is a copy of the input grid, modified as we go along */
1772 digit *grid;
1773 /* row[y*cr+n-1] TRUE if digit n has been placed in row y */
1774 unsigned char *row;
1775 /* col[x*cr+n-1] TRUE if digit n has been placed in row x */
1776 unsigned char *col;
1777 /* blk[(y*c+x)*cr+n-1] TRUE if digit n has been placed in block (x,y) */
1778 unsigned char *blk;
1779 /* This lists all the empty spaces remaining in the grid. */
1780 struct gridgen_coord *spaces;
1781 int nspaces;
1782 /* If we need randomisation in the solve, this is our random state. */
1783 random_state *rs;
1784};
1785
1786/*
1787 * The real recursive step in the generating function.
1788 */
1789static int gridgen_real(struct gridgen_usage *usage, digit *grid)
1790{
1791 int c = usage->c, r = usage->r, cr = usage->cr;
1792 int i, j, n, sx, sy, bestm, bestr, ret;
1793 int *digits;
1794
1795 /*
1796 * Firstly, check for completion! If there are no spaces left
1797 * in the grid, we have a solution.
1798 */
1799 if (usage->nspaces == 0) {
1800 memcpy(grid, usage->grid, cr * cr);
1801 return TRUE;
1802 }
1803
1804 /*
1805 * Otherwise, there must be at least one space. Find the most
1806 * constrained space, using the `r' field as a tie-breaker.
1807 */
1808 bestm = cr+1; /* so that any space will beat it */
1809 bestr = 0;
1810 i = sx = sy = -1;
1811 for (j = 0; j < usage->nspaces; j++) {
1812 int x = usage->spaces[j].x, y = usage->spaces[j].y;
1813 int m;
1814
1815 /*
1816 * Find the number of digits that could go in this space.
1817 */
1818 m = 0;
1819 for (n = 0; n < cr; n++)
1820 if (!usage->row[y*cr+n] && !usage->col[x*cr+n] &&
1821 !usage->blk[((y/c)*c+(x/r))*cr+n])
1822 m++;
1823
1824 if (m < bestm || (m == bestm && usage->spaces[j].r < bestr)) {
1825 bestm = m;
1826 bestr = usage->spaces[j].r;
1827 sx = x;
1828 sy = y;
1829 i = j;
1830 }
1831 }
1832
1833 /*
1834 * Swap that square into the final place in the spaces array,
1835 * so that decrementing nspaces will remove it from the list.
1836 */
1837 if (i != usage->nspaces-1) {
1838 struct gridgen_coord t;
1839 t = usage->spaces[usage->nspaces-1];
1840 usage->spaces[usage->nspaces-1] = usage->spaces[i];
1841 usage->spaces[i] = t;
1842 }
1843
1844 /*
1845 * Now we've decided which square to start our recursion at,
1846 * simply go through all possible values, shuffling them
1847 * randomly first if necessary.
1848 */
1849 digits = snewn(bestm, int);
1850 j = 0;
1851 for (n = 0; n < cr; n++)
1852 if (!usage->row[sy*cr+n] && !usage->col[sx*cr+n] &&
1853 !usage->blk[((sy/c)*c+(sx/r))*cr+n]) {
1854 digits[j++] = n+1;
1855 }
1856
947a07d6 1857 if (usage->rs)
1858 shuffle(digits, j, sizeof(*digits), usage->rs);
ab362080 1859
1860 /* And finally, go through the digit list and actually recurse. */
1861 ret = FALSE;
1862 for (i = 0; i < j; i++) {
1863 n = digits[i];
1864
1865 /* Update the usage structure to reflect the placing of this digit. */
1866 usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
1867 usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = TRUE;
1868 usage->grid[sy*cr+sx] = n;
1869 usage->nspaces--;
1870
1871 /* Call the solver recursively. Stop when we find a solution. */
1872 if (gridgen_real(usage, grid))
1873 ret = TRUE;
1874
1875 /* Revert the usage structure. */
1876 usage->row[sy*cr+n-1] = usage->col[sx*cr+n-1] =
1877 usage->blk[((sy/c)*c+(sx/r))*cr+n-1] = FALSE;
1878 usage->grid[sy*cr+sx] = 0;
1879 usage->nspaces++;
1880
1881 if (ret)
1882 break;
1883 }
1884
1885 sfree(digits);
1886 return ret;
1887}
1888
1889/*
1890 * Entry point to generator. You give it dimensions and a starting
1891 * grid, which is simply an array of cr*cr digits.
1892 */
1893static void gridgen(int c, int r, digit *grid, random_state *rs)
1894{
1895 struct gridgen_usage *usage;
1896 int x, y, cr = c*r;
1897
1898 /*
1899 * Clear the grid to start with.
1900 */
1901 memset(grid, 0, cr*cr);
1902
1903 /*
1904 * Create a gridgen_usage structure.
1905 */
1906 usage = snew(struct gridgen_usage);
1907
1908 usage->c = c;
1909 usage->r = r;
1910 usage->cr = cr;
1911
1912 usage->grid = snewn(cr * cr, digit);
1913 memcpy(usage->grid, grid, cr * cr);
1914
1915 usage->row = snewn(cr * cr, unsigned char);
1916 usage->col = snewn(cr * cr, unsigned char);
1917 usage->blk = snewn(cr * cr, unsigned char);
1918 memset(usage->row, FALSE, cr * cr);
1919 memset(usage->col, FALSE, cr * cr);
1920 memset(usage->blk, FALSE, cr * cr);
1921
1922 usage->spaces = snewn(cr * cr, struct gridgen_coord);
1923 usage->nspaces = 0;
1924
1925 usage->rs = rs;
1926
1927 /*
1928 * Initialise the list of grid spaces.
1929 */
1930 for (y = 0; y < cr; y++) {
1931 for (x = 0; x < cr; x++) {
1932 usage->spaces[usage->nspaces].x = x;
1933 usage->spaces[usage->nspaces].y = y;
1934 usage->spaces[usage->nspaces].r = random_bits(rs, 31);
1935 usage->nspaces++;
1936 }
1937 }
1938
1939 /*
1940 * Run the real generator function.
1941 */
1942 gridgen_real(usage, grid);
1943
1944 /*
1945 * Clean up the usage structure now we have our answer.
1946 */
1947 sfree(usage->spaces);
1948 sfree(usage->blk);
1949 sfree(usage->col);
1950 sfree(usage->row);
1951 sfree(usage->grid);
1952 sfree(usage);
1953}
1954
1955/* ----------------------------------------------------------------------
1956 * End of grid generator code.
1d8e8ad8 1957 */
1958
1959/*
1960 * Check whether a grid contains a valid complete puzzle.
1961 */
1962static int check_valid(int c, int r, digit *grid)
1963{
1964 int cr = c*r;
1965 unsigned char *used;
1966 int x, y, n;
1967
1968 used = snewn(cr, unsigned char);
1969
1970 /*
1971 * Check that each row contains precisely one of everything.
1972 */
1973 for (y = 0; y < cr; y++) {
1974 memset(used, FALSE, cr);
1975 for (x = 0; x < cr; x++)
1976 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
1977 used[grid[y*cr+x]-1] = TRUE;
1978 for (n = 0; n < cr; n++)
1979 if (!used[n]) {
1980 sfree(used);
1981 return FALSE;
1982 }
1983 }
1984
1985 /*
1986 * Check that each column contains precisely one of everything.
1987 */
1988 for (x = 0; x < cr; x++) {
1989 memset(used, FALSE, cr);
1990 for (y = 0; y < cr; y++)
1991 if (grid[y*cr+x] > 0 && grid[y*cr+x] <= cr)
1992 used[grid[y*cr+x]-1] = TRUE;
1993 for (n = 0; n < cr; n++)
1994 if (!used[n]) {
1995 sfree(used);
1996 return FALSE;
1997 }
1998 }
1999
2000 /*
2001 * Check that each block contains precisely one of everything.
2002 */
2003 for (x = 0; x < cr; x += r) {
2004 for (y = 0; y < cr; y += c) {
2005 int xx, yy;
2006 memset(used, FALSE, cr);
2007 for (xx = x; xx < x+r; xx++)
2008 for (yy = 0; yy < y+c; yy++)
2009 if (grid[yy*cr+xx] > 0 && grid[yy*cr+xx] <= cr)
2010 used[grid[yy*cr+xx]-1] = TRUE;
2011 for (n = 0; n < cr; n++)
2012 if (!used[n]) {
2013 sfree(used);
2014 return FALSE;
2015 }
2016 }
2017 }
2018
2019 sfree(used);
2020 return TRUE;
2021}
2022
ef57b17d 2023static int symmetries(game_params *params, int x, int y, int *output, int s)
2024{
2025 int c = params->c, r = params->r, cr = c*r;
2026 int i = 0;
2027
154bf9b1 2028#define ADD(x,y) (*output++ = (x), *output++ = (y), i++)
2029
2030 ADD(x, y);
ef57b17d 2031
2032 switch (s) {
2033 case SYMM_NONE:
2034 break; /* just x,y is all we need */
ef57b17d 2035 case SYMM_ROT2:
154bf9b1 2036 ADD(cr - 1 - x, cr - 1 - y);
2037 break;
2038 case SYMM_ROT4:
2039 ADD(cr - 1 - y, x);
2040 ADD(y, cr - 1 - x);
2041 ADD(cr - 1 - x, cr - 1 - y);
2042 break;
2043 case SYMM_REF2:
2044 ADD(cr - 1 - x, y);
2045 break;
2046 case SYMM_REF2D:
2047 ADD(y, x);
2048 break;
2049 case SYMM_REF4:
2050 ADD(cr - 1 - x, y);
2051 ADD(x, cr - 1 - y);
2052 ADD(cr - 1 - x, cr - 1 - y);
2053 break;
2054 case SYMM_REF4D:
2055 ADD(y, x);
2056 ADD(cr - 1 - x, cr - 1 - y);
2057 ADD(cr - 1 - y, cr - 1 - x);
2058 break;
2059 case SYMM_REF8:
2060 ADD(cr - 1 - x, y);
2061 ADD(x, cr - 1 - y);
2062 ADD(cr - 1 - x, cr - 1 - y);
2063 ADD(y, x);
2064 ADD(y, cr - 1 - x);
2065 ADD(cr - 1 - y, x);
2066 ADD(cr - 1 - y, cr - 1 - x);
2067 break;
ef57b17d 2068 }
2069
154bf9b1 2070#undef ADD
2071
ef57b17d 2072 return i;
2073}
2074
c566778e 2075static char *encode_solve_move(int cr, digit *grid)
2076{
2077 int i, len;
2078 char *ret, *p, *sep;
2079
2080 /*
2081 * It's surprisingly easy to work out _exactly_ how long this
2082 * string needs to be. To decimal-encode all the numbers from 1
2083 * to n:
2084 *
2085 * - every number has a units digit; total is n.
2086 * - all numbers above 9 have a tens digit; total is max(n-9,0).
2087 * - all numbers above 99 have a hundreds digit; total is max(n-99,0).
2088 * - and so on.
2089 */
2090 len = 0;
2091 for (i = 1; i <= cr; i *= 10)
2092 len += max(cr - i + 1, 0);
2093 len += cr; /* don't forget the commas */
2094 len *= cr; /* there are cr rows of these */
2095
2096 /*
2097 * Now len is one bigger than the total size of the
2098 * comma-separated numbers (because we counted an
2099 * additional leading comma). We need to have a leading S
2100 * and a trailing NUL, so we're off by one in total.
2101 */
2102 len++;
2103
2104 ret = snewn(len, char);
2105 p = ret;
2106 *p++ = 'S';
2107 sep = "";
2108 for (i = 0; i < cr*cr; i++) {
2109 p += sprintf(p, "%s%d", sep, grid[i]);
2110 sep = ",";
2111 }
2112 *p++ = '\0';
2113 assert(p - ret == len);
2114
2115 return ret;
2116}
3220eba4 2117
1185e3c5 2118static char *new_game_desc(game_params *params, random_state *rs,
c566778e 2119 char **aux, int interactive)
1d8e8ad8 2120{
2121 int c = params->c, r = params->r, cr = c*r;
2122 int area = cr*cr;
2123 digit *grid, *grid2;
2124 struct xy { int x, y; } *locs;
2125 int nlocs;
1185e3c5 2126 char *desc;
ef57b17d 2127 int coords[16], ncoords;
1af60e1e 2128 int maxdiff;
2129 int x, y, i, j;
1d8e8ad8 2130
2131 /*
7c568a48 2132 * Adjust the maximum difficulty level to be consistent with
2133 * the puzzle size: all 2x2 puzzles appear to be Trivial
2134 * (DIFF_BLOCK) so we cannot hold out for even a Basic
2135 * (DIFF_SIMPLE) one.
1d8e8ad8 2136 */
7c568a48 2137 maxdiff = params->diff;
2138 if (c == 2 && r == 2)
2139 maxdiff = DIFF_BLOCK;
1d8e8ad8 2140
7c568a48 2141 grid = snewn(area, digit);
ef57b17d 2142 locs = snewn(area, struct xy);
1d8e8ad8 2143 grid2 = snewn(area, digit);
1d8e8ad8 2144
7c568a48 2145 /*
2146 * Loop until we get a grid of the required difficulty. This is
2147 * nasty, but it seems to be unpleasantly hard to generate
2148 * difficult grids otherwise.
2149 */
2150 do {
2151 /*
ab362080 2152 * Generate a random solved state.
7c568a48 2153 */
ab362080 2154 gridgen(c, r, grid, rs);
7c568a48 2155 assert(check_valid(c, r, grid));
2156
3220eba4 2157 /*
c566778e 2158 * Save the solved grid in aux.
3220eba4 2159 */
2160 {
ab53eb64 2161 /*
2162 * We might already have written *aux the last time we
2163 * went round this loop, in which case we should free
c566778e 2164 * the old aux before overwriting it with the new one.
ab53eb64 2165 */
2166 if (*aux) {
ab53eb64 2167 sfree(*aux);
2168 }
c566778e 2169
2170 *aux = encode_solve_move(cr, grid);
3220eba4 2171 }
2172
7c568a48 2173 /*
2174 * Now we have a solved grid, start removing things from it
2175 * while preserving solubility.
2176 */
7c568a48 2177
1af60e1e 2178 /*
2179 * Find the set of equivalence classes of squares permitted
2180 * by the selected symmetry. We do this by enumerating all
2181 * the grid squares which have no symmetric companion
2182 * sorting lower than themselves.
2183 */
2184 nlocs = 0;
2185 for (y = 0; y < cr; y++)
2186 for (x = 0; x < cr; x++) {
2187 int i = y*cr+x;
2188 int j;
7c568a48 2189
1af60e1e 2190 ncoords = symmetries(params, x, y, coords, params->symm);
2191 for (j = 0; j < ncoords; j++)
2192 if (coords[2*j+1]*cr+coords[2*j] < i)
2193 break;
2194 if (j == ncoords) {
154bf9b1 2195 locs[nlocs].x = x;
2196 locs[nlocs].y = y;
2197 nlocs++;
2198 }
2199 }
7c568a48 2200
1af60e1e 2201 /*
2202 * Now shuffle that list.
2203 */
2204 shuffle(locs, nlocs, sizeof(*locs), rs);
de60d8bd 2205
1af60e1e 2206 /*
2207 * Now loop over the shuffled list and, for each element,
2208 * see whether removing that element (and its reflections)
2209 * from the grid will still leave the grid soluble.
2210 */
2211 for (i = 0; i < nlocs; i++) {
2212 int ret;
7c568a48 2213
1af60e1e 2214 x = locs[i].x;
2215 y = locs[i].y;
7c568a48 2216
1af60e1e 2217 memcpy(grid2, grid, area);
2218 ncoords = symmetries(params, x, y, coords, params->symm);
2219 for (j = 0; j < ncoords; j++)
2220 grid2[coords[2*j+1]*cr+coords[2*j]] = 0;
7c568a48 2221
1af60e1e 2222 ret = solver(c, r, grid2, maxdiff);
437ed08c 2223 if (ret <= maxdiff) {
1af60e1e 2224 for (j = 0; j < ncoords; j++)
2225 grid[coords[2*j+1]*cr+coords[2*j]] = 0;
7c568a48 2226 }
2227 }
1d8e8ad8 2228
7c568a48 2229 memcpy(grid2, grid, area);
947a07d6 2230 } while (solver(c, r, grid2, maxdiff) < maxdiff);
1d8e8ad8 2231
1d8e8ad8 2232 sfree(grid2);
2233 sfree(locs);
2234
1d8e8ad8 2235 /*
2236 * Now we have the grid as it will be presented to the user.
1185e3c5 2237 * Encode it in a game desc.
1d8e8ad8 2238 */
2239 {
2240 char *p;
2241 int run, i;
2242
1185e3c5 2243 desc = snewn(5 * area, char);
2244 p = desc;
1d8e8ad8 2245 run = 0;
2246 for (i = 0; i <= area; i++) {
2247 int n = (i < area ? grid[i] : -1);
2248
2249 if (!n)
2250 run++;
2251 else {
2252 if (run) {
2253 while (run > 0) {
2254 int c = 'a' - 1 + run;
2255 if (run > 26)
2256 c = 'z';
2257 *p++ = c;
2258 run -= c - ('a' - 1);
2259 }
2260 } else {
2261 /*
2262 * If there's a number in the very top left or
2263 * bottom right, there's no point putting an
2264 * unnecessary _ before or after it.
2265 */
1185e3c5 2266 if (p > desc && n > 0)
1d8e8ad8 2267 *p++ = '_';
2268 }
2269 if (n > 0)
2270 p += sprintf(p, "%d", n);
2271 run = 0;
2272 }
2273 }
1185e3c5 2274 assert(p - desc < 5 * area);
1d8e8ad8 2275 *p++ = '\0';
1185e3c5 2276 desc = sresize(desc, p - desc, char);
1d8e8ad8 2277 }
2278
2279 sfree(grid);
2280
1185e3c5 2281 return desc;
1d8e8ad8 2282}
2283
1185e3c5 2284static char *validate_desc(game_params *params, char *desc)
1d8e8ad8 2285{
2286 int area = params->r * params->r * params->c * params->c;
2287 int squares = 0;
2288
1185e3c5 2289 while (*desc) {
2290 int n = *desc++;
1d8e8ad8 2291 if (n >= 'a' && n <= 'z') {
2292 squares += n - 'a' + 1;
2293 } else if (n == '_') {
2294 /* do nothing */;
2295 } else if (n > '0' && n <= '9') {
d0ed57cd 2296 int val = atoi(desc-1);
2297 if (val < 1 || val > params->c * params->r)
2298 return "Out-of-range number in game description";
1d8e8ad8 2299 squares++;
1185e3c5 2300 while (*desc >= '0' && *desc <= '9')
2301 desc++;
1d8e8ad8 2302 } else
1185e3c5 2303 return "Invalid character in game description";
1d8e8ad8 2304 }
2305
2306 if (squares < area)
2307 return "Not enough data to fill grid";
2308
2309 if (squares > area)
2310 return "Too much data to fit in grid";
2311
2312 return NULL;
2313}
2314
dafd6cf6 2315static game_state *new_game(midend *me, game_params *params, char *desc)
1d8e8ad8 2316{
2317 game_state *state = snew(game_state);
2318 int c = params->c, r = params->r, cr = c*r, area = cr * cr;
2319 int i;
2320
2321 state->c = params->c;
2322 state->r = params->r;
2323
2324 state->grid = snewn(area, digit);
c8266e03 2325 state->pencil = snewn(area * cr, unsigned char);
2326 memset(state->pencil, 0, area * cr);
1d8e8ad8 2327 state->immutable = snewn(area, unsigned char);
2328 memset(state->immutable, FALSE, area);
2329
2ac6d24e 2330 state->completed = state->cheated = FALSE;
1d8e8ad8 2331
2332 i = 0;
1185e3c5 2333 while (*desc) {
2334 int n = *desc++;
1d8e8ad8 2335 if (n >= 'a' && n <= 'z') {
2336 int run = n - 'a' + 1;
2337 assert(i + run <= area);
2338 while (run-- > 0)
2339 state->grid[i++] = 0;
2340 } else if (n == '_') {
2341 /* do nothing */;
2342 } else if (n > '0' && n <= '9') {
2343 assert(i < area);
2344 state->immutable[i] = TRUE;
1185e3c5 2345 state->grid[i++] = atoi(desc-1);
2346 while (*desc >= '0' && *desc <= '9')
2347 desc++;
1d8e8ad8 2348 } else {
2349 assert(!"We can't get here");
2350 }
2351 }
2352 assert(i == area);
2353
2354 return state;
2355}
2356
2357static game_state *dup_game(game_state *state)
2358{
2359 game_state *ret = snew(game_state);
2360 int c = state->c, r = state->r, cr = c*r, area = cr * cr;
2361
2362 ret->c = state->c;
2363 ret->r = state->r;
2364
2365 ret->grid = snewn(area, digit);
2366 memcpy(ret->grid, state->grid, area);
2367
c8266e03 2368 ret->pencil = snewn(area * cr, unsigned char);
2369 memcpy(ret->pencil, state->pencil, area * cr);
2370
1d8e8ad8 2371 ret->immutable = snewn(area, unsigned char);
2372 memcpy(ret->immutable, state->immutable, area);
2373
2374 ret->completed = state->completed;
2ac6d24e 2375 ret->cheated = state->cheated;
1d8e8ad8 2376
2377 return ret;
2378}
2379
2380static void free_game(game_state *state)
2381{
2382 sfree(state->immutable);
c8266e03 2383 sfree(state->pencil);
1d8e8ad8 2384 sfree(state->grid);
2385 sfree(state);
2386}
2387
df11cd4e 2388static char *solve_game(game_state *state, game_state *currstate,
c566778e 2389 char *ai, char **error)
2ac6d24e 2390{
3220eba4 2391 int c = state->c, r = state->r, cr = c*r;
c566778e 2392 char *ret;
df11cd4e 2393 digit *grid;
ab362080 2394 int solve_ret;
2ac6d24e 2395
3220eba4 2396 /*
c566778e 2397 * If we already have the solution in ai, save ourselves some
2398 * time.
3220eba4 2399 */
c566778e 2400 if (ai)
2401 return dupstr(ai);
3220eba4 2402
c566778e 2403 grid = snewn(cr*cr, digit);
2404 memcpy(grid, state->grid, cr*cr);
947a07d6 2405 solve_ret = solver(c, r, grid, DIFF_RECURSIVE);
ab362080 2406
2407 *error = NULL;
df11cd4e 2408
ab362080 2409 if (solve_ret == DIFF_IMPOSSIBLE)
2410 *error = "No solution exists for this puzzle";
2411 else if (solve_ret == DIFF_AMBIGUOUS)
2412 *error = "Multiple solutions exist for this puzzle";
2413
2414 if (*error) {
c566778e 2415 sfree(grid);
c566778e 2416 return NULL;
df11cd4e 2417 }
2418
c566778e 2419 ret = encode_solve_move(cr, grid);
df11cd4e 2420
c566778e 2421 sfree(grid);
2ac6d24e 2422
2423 return ret;
2424}
2425
9b4b03d3 2426static char *grid_text_format(int c, int r, digit *grid)
2427{
2428 int cr = c*r;
2429 int x, y;
2430 int maxlen;
2431 char *ret, *p;
2432
2433 /*
2434 * There are cr lines of digits, plus r-1 lines of block
2435 * separators. Each line contains cr digits, cr-1 separating
2436 * spaces, and c-1 two-character block separators. Thus, the
2437 * total length of a line is 2*cr+2*c-3 (not counting the
2438 * newline), and there are cr+r-1 of them.
2439 */
2440 maxlen = (cr+r-1) * (2*cr+2*c-2);
2441 ret = snewn(maxlen+1, char);
2442 p = ret;
2443
2444 for (y = 0; y < cr; y++) {
2445 for (x = 0; x < cr; x++) {
2446 int ch = grid[y * cr + x];
2447 if (ch == 0)
59b4cf3c 2448 ch = '.';
9b4b03d3 2449 else if (ch <= 9)
2450 ch = '0' + ch;
2451 else
2452 ch = 'a' + ch-10;
2453 *p++ = ch;
2454 if (x+1 < cr) {
2455 *p++ = ' ';
2456 if ((x+1) % r == 0) {
2457 *p++ = '|';
2458 *p++ = ' ';
2459 }
2460 }
2461 }
2462 *p++ = '\n';
2463 if (y+1 < cr && (y+1) % c == 0) {
2464 for (x = 0; x < cr; x++) {
2465 *p++ = '-';
2466 if (x+1 < cr) {
2467 *p++ = '-';
2468 if ((x+1) % r == 0) {
2469 *p++ = '+';
2470 *p++ = '-';
2471 }
2472 }
2473 }
2474 *p++ = '\n';
2475 }
2476 }
2477
2478 assert(p - ret == maxlen);
2479 *p = '\0';
2480 return ret;
2481}
2482
2483static char *game_text_format(game_state *state)
2484{
2485 return grid_text_format(state->c, state->r, state->grid);
2486}
2487
1d8e8ad8 2488struct game_ui {
2489 /*
2490 * These are the coordinates of the currently highlighted
2491 * square on the grid, or -1,-1 if there isn't one. When there
2492 * is, pressing a valid number or letter key or Space will
2493 * enter that number or letter in the grid.
2494 */
2495 int hx, hy;
c8266e03 2496 /*
2497 * This indicates whether the current highlight is a
2498 * pencil-mark one or a real one.
2499 */
2500 int hpencil;
1d8e8ad8 2501};
2502
2503static game_ui *new_ui(game_state *state)
2504{
2505 game_ui *ui = snew(game_ui);
2506
2507 ui->hx = ui->hy = -1;
c8266e03 2508 ui->hpencil = 0;
1d8e8ad8 2509
2510 return ui;
2511}
2512
2513static void free_ui(game_ui *ui)
2514{
2515 sfree(ui);
2516}
2517
844f605f 2518static char *encode_ui(game_ui *ui)
ae8290c6 2519{
2520 return NULL;
2521}
2522
844f605f 2523static void decode_ui(game_ui *ui, char *encoding)
ae8290c6 2524{
2525}
2526
07dfb697 2527static void game_changed_state(game_ui *ui, game_state *oldstate,
2528 game_state *newstate)
2529{
2530 int c = newstate->c, r = newstate->r, cr = c*r;
2531 /*
2532 * We prevent pencil-mode highlighting of a filled square. So
2533 * if the user has just filled in a square which we had a
2534 * pencil-mode highlight in (by Undo, or by Redo, or by Solve),
2535 * then we cancel the highlight.
2536 */
2537 if (ui->hx >= 0 && ui->hy >= 0 && ui->hpencil &&
2538 newstate->grid[ui->hy * cr + ui->hx] != 0) {
2539 ui->hx = ui->hy = -1;
2540 }
2541}
2542
1e3e152d 2543struct game_drawstate {
2544 int started;
2545 int c, r, cr;
2546 int tilesize;
2547 digit *grid;
2548 unsigned char *pencil;
2549 unsigned char *hl;
2550 /* This is scratch space used within a single call to game_redraw. */
2551 int *entered_items;
2552};
2553
df11cd4e 2554static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2555 int x, int y, int button)
1d8e8ad8 2556{
df11cd4e 2557 int c = state->c, r = state->r, cr = c*r;
1d8e8ad8 2558 int tx, ty;
df11cd4e 2559 char buf[80];
1d8e8ad8 2560
f0ee053c 2561 button &= ~MOD_MASK;
3c833d45 2562
ae812854 2563 tx = (x + TILE_SIZE - BORDER) / TILE_SIZE - 1;
2564 ty = (y + TILE_SIZE - BORDER) / TILE_SIZE - 1;
1d8e8ad8 2565
39d682c9 2566 if (tx >= 0 && tx < cr && ty >= 0 && ty < cr) {
2567 if (button == LEFT_BUTTON) {
df11cd4e 2568 if (state->immutable[ty*cr+tx]) {
39d682c9 2569 ui->hx = ui->hy = -1;
2570 } else if (tx == ui->hx && ty == ui->hy && ui->hpencil == 0) {
2571 ui->hx = ui->hy = -1;
2572 } else {
2573 ui->hx = tx;
2574 ui->hy = ty;
2575 ui->hpencil = 0;
2576 }
df11cd4e 2577 return ""; /* UI activity occurred */
39d682c9 2578 }
2579 if (button == RIGHT_BUTTON) {
2580 /*
2581 * Pencil-mode highlighting for non filled squares.
2582 */
df11cd4e 2583 if (state->grid[ty*cr+tx] == 0) {
39d682c9 2584 if (tx == ui->hx && ty == ui->hy && ui->hpencil) {
2585 ui->hx = ui->hy = -1;
2586 } else {
2587 ui->hpencil = 1;
2588 ui->hx = tx;
2589 ui->hy = ty;
2590 }
2591 } else {
2592 ui->hx = ui->hy = -1;
2593 }
df11cd4e 2594 return ""; /* UI activity occurred */
39d682c9 2595 }
1d8e8ad8 2596 }
2597
2598 if (ui->hx != -1 && ui->hy != -1 &&
2599 ((button >= '1' && button <= '9' && button - '0' <= cr) ||
2600 (button >= 'a' && button <= 'z' && button - 'a' + 10 <= cr) ||
2601 (button >= 'A' && button <= 'Z' && button - 'A' + 10 <= cr) ||
0eb4d76e 2602 button == ' ' || button == '\010' || button == '\177')) {
1d8e8ad8 2603 int n = button - '0';
2604 if (button >= 'A' && button <= 'Z')
2605 n = button - 'A' + 10;
2606 if (button >= 'a' && button <= 'z')
2607 n = button - 'a' + 10;
0eb4d76e 2608 if (button == ' ' || button == '\010' || button == '\177')
1d8e8ad8 2609 n = 0;
2610
39d682c9 2611 /*
2612 * Can't overwrite this square. In principle this shouldn't
2613 * happen anyway because we should never have even been
2614 * able to highlight the square, but it never hurts to be
2615 * careful.
2616 */
df11cd4e 2617 if (state->immutable[ui->hy*cr+ui->hx])
39d682c9 2618 return NULL;
1d8e8ad8 2619
c8266e03 2620 /*
2621 * Can't make pencil marks in a filled square. In principle
2622 * this shouldn't happen anyway because we should never
2623 * have even been able to pencil-highlight the square, but
2624 * it never hurts to be careful.
2625 */
df11cd4e 2626 if (ui->hpencil && state->grid[ui->hy*cr+ui->hx])
c8266e03 2627 return NULL;
2628
df11cd4e 2629 sprintf(buf, "%c%d,%d,%d",
871bf294 2630 (char)(ui->hpencil && n > 0 ? 'P' : 'R'), ui->hx, ui->hy, n);
df11cd4e 2631
2632 ui->hx = ui->hy = -1;
2633
2634 return dupstr(buf);
2635 }
2636
2637 return NULL;
2638}
2639
2640static game_state *execute_move(game_state *from, char *move)
2641{
2642 int c = from->c, r = from->r, cr = c*r;
2643 game_state *ret;
2644 int x, y, n;
2645
2646 if (move[0] == 'S') {
2647 char *p;
2648
1d8e8ad8 2649 ret = dup_game(from);
df11cd4e 2650 ret->completed = ret->cheated = TRUE;
2651
2652 p = move+1;
2653 for (n = 0; n < cr*cr; n++) {
2654 ret->grid[n] = atoi(p);
2655
2656 if (!*p || ret->grid[n] < 1 || ret->grid[n] > cr) {
2657 free_game(ret);
2658 return NULL;
2659 }
2660
2661 while (*p && isdigit((unsigned char)*p)) p++;
2662 if (*p == ',') p++;
2663 }
2664
2665 return ret;
2666 } else if ((move[0] == 'P' || move[0] == 'R') &&
2667 sscanf(move+1, "%d,%d,%d", &x, &y, &n) == 3 &&
2668 x >= 0 && x < cr && y >= 0 && y < cr && n >= 0 && n <= cr) {
2669
2670 ret = dup_game(from);
2671 if (move[0] == 'P' && n > 0) {
2672 int index = (y*cr+x) * cr + (n-1);
c8266e03 2673 ret->pencil[index] = !ret->pencil[index];
2674 } else {
df11cd4e 2675 ret->grid[y*cr+x] = n;
2676 memset(ret->pencil + (y*cr+x)*cr, 0, cr);
1d8e8ad8 2677
c8266e03 2678 /*
2679 * We've made a real change to the grid. Check to see
2680 * if the game has been completed.
2681 */
2682 if (!ret->completed && check_valid(c, r, ret->grid)) {
2683 ret->completed = TRUE;
2684 }
2685 }
df11cd4e 2686 return ret;
2687 } else
2688 return NULL; /* couldn't parse move string */
1d8e8ad8 2689}
2690
2691/* ----------------------------------------------------------------------
2692 * Drawing routines.
2693 */
2694
1e3e152d 2695#define SIZE(cr) ((cr) * TILE_SIZE + 2*BORDER + 1)
871bf294 2696#define GETTILESIZE(cr, w) ( (double)(w-1) / (double)(cr+1) )
1d8e8ad8 2697
1f3ee4ee 2698static void game_compute_size(game_params *params, int tilesize,
2699 int *x, int *y)
1d8e8ad8 2700{
1f3ee4ee 2701 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2702 struct { int tilesize; } ads, *ds = &ads;
2703 ads.tilesize = tilesize;
1e3e152d 2704
1f3ee4ee 2705 *x = SIZE(params->c * params->r);
2706 *y = SIZE(params->c * params->r);
2707}
1d8e8ad8 2708
dafd6cf6 2709static void game_set_size(drawing *dr, game_drawstate *ds,
2710 game_params *params, int tilesize)
1f3ee4ee 2711{
2712 ds->tilesize = tilesize;
1d8e8ad8 2713}
2714
8266f3fc 2715static float *game_colours(frontend *fe, int *ncolours)
1d8e8ad8 2716{
2717 float *ret = snewn(3 * NCOLOURS, float);
2718
2719 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2720
2721 ret[COL_GRID * 3 + 0] = 0.0F;
2722 ret[COL_GRID * 3 + 1] = 0.0F;
2723 ret[COL_GRID * 3 + 2] = 0.0F;
2724
2725 ret[COL_CLUE * 3 + 0] = 0.0F;
2726 ret[COL_CLUE * 3 + 1] = 0.0F;
2727 ret[COL_CLUE * 3 + 2] = 0.0F;
2728
2729 ret[COL_USER * 3 + 0] = 0.0F;
2730 ret[COL_USER * 3 + 1] = 0.6F * ret[COL_BACKGROUND * 3 + 1];
2731 ret[COL_USER * 3 + 2] = 0.0F;
2732
2733 ret[COL_HIGHLIGHT * 3 + 0] = 0.85F * ret[COL_BACKGROUND * 3 + 0];
2734 ret[COL_HIGHLIGHT * 3 + 1] = 0.85F * ret[COL_BACKGROUND * 3 + 1];
2735 ret[COL_HIGHLIGHT * 3 + 2] = 0.85F * ret[COL_BACKGROUND * 3 + 2];
2736
7b14a9ec 2737 ret[COL_ERROR * 3 + 0] = 1.0F;
2738 ret[COL_ERROR * 3 + 1] = 0.0F;
2739 ret[COL_ERROR * 3 + 2] = 0.0F;
2740
c8266e03 2741 ret[COL_PENCIL * 3 + 0] = 0.5F * ret[COL_BACKGROUND * 3 + 0];
2742 ret[COL_PENCIL * 3 + 1] = 0.5F * ret[COL_BACKGROUND * 3 + 1];
2743 ret[COL_PENCIL * 3 + 2] = ret[COL_BACKGROUND * 3 + 2];
2744
1d8e8ad8 2745 *ncolours = NCOLOURS;
2746 return ret;
2747}
2748
dafd6cf6 2749static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
1d8e8ad8 2750{
2751 struct game_drawstate *ds = snew(struct game_drawstate);
2752 int c = state->c, r = state->r, cr = c*r;
2753
2754 ds->started = FALSE;
2755 ds->c = c;
2756 ds->r = r;
2757 ds->cr = cr;
2758 ds->grid = snewn(cr*cr, digit);
2759 memset(ds->grid, 0, cr*cr);
c8266e03 2760 ds->pencil = snewn(cr*cr*cr, digit);
2761 memset(ds->pencil, 0, cr*cr*cr);
1d8e8ad8 2762 ds->hl = snewn(cr*cr, unsigned char);
2763 memset(ds->hl, 0, cr*cr);
b71dd7fc 2764 ds->entered_items = snewn(cr*cr, int);
1e3e152d 2765 ds->tilesize = 0; /* not decided yet */
1d8e8ad8 2766 return ds;
2767}
2768
dafd6cf6 2769static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1d8e8ad8 2770{
2771 sfree(ds->hl);
c8266e03 2772 sfree(ds->pencil);
1d8e8ad8 2773 sfree(ds->grid);
b71dd7fc 2774 sfree(ds->entered_items);
1d8e8ad8 2775 sfree(ds);
2776}
2777
dafd6cf6 2778static void draw_number(drawing *dr, game_drawstate *ds, game_state *state,
1d8e8ad8 2779 int x, int y, int hl)
2780{
2781 int c = state->c, r = state->r, cr = c*r;
2782 int tx, ty;
2783 int cx, cy, cw, ch;
2784 char str[2];
2785
c8266e03 2786 if (ds->grid[y*cr+x] == state->grid[y*cr+x] &&
2787 ds->hl[y*cr+x] == hl &&
2788 !memcmp(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr))
1d8e8ad8 2789 return; /* no change required */
2790
2791 tx = BORDER + x * TILE_SIZE + 2;
2792 ty = BORDER + y * TILE_SIZE + 2;
2793
2794 cx = tx;
2795 cy = ty;
2796 cw = TILE_SIZE-3;
2797 ch = TILE_SIZE-3;
2798
2799 if (x % r)
2800 cx--, cw++;
2801 if ((x+1) % r)
2802 cw++;
2803 if (y % c)
2804 cy--, ch++;
2805 if ((y+1) % c)
2806 ch++;
2807
dafd6cf6 2808 clip(dr, cx, cy, cw, ch);
1d8e8ad8 2809
c8266e03 2810 /* background needs erasing */
dafd6cf6 2811 draw_rect(dr, cx, cy, cw, ch, (hl & 15) == 1 ? COL_HIGHLIGHT : COL_BACKGROUND);
c8266e03 2812
2813 /* pencil-mode highlight */
7b14a9ec 2814 if ((hl & 15) == 2) {
c8266e03 2815 int coords[6];
2816 coords[0] = cx;
2817 coords[1] = cy;
2818 coords[2] = cx+cw/2;
2819 coords[3] = cy;
2820 coords[4] = cx;
2821 coords[5] = cy+ch/2;
dafd6cf6 2822 draw_polygon(dr, coords, 3, COL_HIGHLIGHT, COL_HIGHLIGHT);
c8266e03 2823 }
1d8e8ad8 2824
2825 /* new number needs drawing? */
2826 if (state->grid[y*cr+x]) {
2827 str[1] = '\0';
2828 str[0] = state->grid[y*cr+x] + '0';
2829 if (str[0] > '9')
2830 str[0] += 'a' - ('9'+1);
dafd6cf6 2831 draw_text(dr, tx + TILE_SIZE/2, ty + TILE_SIZE/2,
1d8e8ad8 2832 FONT_VARIABLE, TILE_SIZE/2, ALIGN_VCENTRE | ALIGN_HCENTRE,
7b14a9ec 2833 state->immutable[y*cr+x] ? COL_CLUE : (hl & 16) ? COL_ERROR : COL_USER, str);
c8266e03 2834 } else {
edf63745 2835 int i, j, npencil;
2836 int pw, ph, pmax, fontsize;
2837
2838 /* count the pencil marks required */
2839 for (i = npencil = 0; i < cr; i++)
2840 if (state->pencil[(y*cr+x)*cr+i])
2841 npencil++;
2842
2843 /*
2844 * It's not sensible to arrange pencil marks in the same
2845 * layout as the squares within a block, because this leads
2846 * to the font being too small. Instead, we arrange pencil
2847 * marks in the nearest thing we can to a square layout,
2848 * and we adjust the square layout depending on the number
2849 * of pencil marks in the square.
2850 */
2851 for (pw = 1; pw * pw < npencil; pw++);
2852 if (pw < 3) pw = 3; /* otherwise it just looks _silly_ */
2853 ph = (npencil + pw - 1) / pw;
2854 if (ph < 2) ph = 2; /* likewise */
2855 pmax = max(pw, ph);
2856 fontsize = TILE_SIZE/(pmax*(11-pmax)/8);
c8266e03 2857
2858 for (i = j = 0; i < cr; i++)
2859 if (state->pencil[(y*cr+x)*cr+i]) {
edf63745 2860 int dx = j % pw, dy = j / pw;
2861
c8266e03 2862 str[1] = '\0';
2863 str[0] = i + '1';
2864 if (str[0] > '9')
2865 str[0] += 'a' - ('9'+1);
dafd6cf6 2866 draw_text(dr, tx + (4*dx+3) * TILE_SIZE / (4*pw+2),
edf63745 2867 ty + (4*dy+3) * TILE_SIZE / (4*ph+2),
2868 FONT_VARIABLE, fontsize,
c8266e03 2869 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_PENCIL, str);
2870 j++;
2871 }
1d8e8ad8 2872 }
2873
dafd6cf6 2874 unclip(dr);
1d8e8ad8 2875
dafd6cf6 2876 draw_update(dr, cx, cy, cw, ch);
1d8e8ad8 2877
2878 ds->grid[y*cr+x] = state->grid[y*cr+x];
c8266e03 2879 memcpy(ds->pencil+(y*cr+x)*cr, state->pencil+(y*cr+x)*cr, cr);
1d8e8ad8 2880 ds->hl[y*cr+x] = hl;
2881}
2882
dafd6cf6 2883static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
1d8e8ad8 2884 game_state *state, int dir, game_ui *ui,
2885 float animtime, float flashtime)
2886{
2887 int c = state->c, r = state->r, cr = c*r;
2888 int x, y;
2889
2890 if (!ds->started) {
2891 /*
2892 * The initial contents of the window are not guaranteed
2893 * and can vary with front ends. To be on the safe side,
2894 * all games should start by drawing a big
2895 * background-colour rectangle covering the whole window.
2896 */
dafd6cf6 2897 draw_rect(dr, 0, 0, SIZE(cr), SIZE(cr), COL_BACKGROUND);
1d8e8ad8 2898
2899 /*
2900 * Draw the grid.
2901 */
2902 for (x = 0; x <= cr; x++) {
2903 int thick = (x % r ? 0 : 1);
dafd6cf6 2904 draw_rect(dr, BORDER + x*TILE_SIZE - thick, BORDER-1,
1d8e8ad8 2905 1+2*thick, cr*TILE_SIZE+3, COL_GRID);
2906 }
2907 for (y = 0; y <= cr; y++) {
2908 int thick = (y % c ? 0 : 1);
dafd6cf6 2909 draw_rect(dr, BORDER-1, BORDER + y*TILE_SIZE - thick,
1d8e8ad8 2910 cr*TILE_SIZE+3, 1+2*thick, COL_GRID);
2911 }
2912 }
2913
2914 /*
7b14a9ec 2915 * This array is used to keep track of rows, columns and boxes
2916 * which contain a number more than once.
2917 */
2918 for (x = 0; x < cr * cr; x++)
b71dd7fc 2919 ds->entered_items[x] = 0;
7b14a9ec 2920 for (x = 0; x < cr; x++)
2921 for (y = 0; y < cr; y++) {
2922 digit d = state->grid[y*cr+x];
2923 if (d) {
2924 int box = (x/r)+(y/c)*c;
b71dd7fc 2925 ds->entered_items[x*cr+d-1] |= ((ds->entered_items[x*cr+d-1] & 1) << 1) | 1;
2926 ds->entered_items[y*cr+d-1] |= ((ds->entered_items[y*cr+d-1] & 4) << 1) | 4;
2927 ds->entered_items[box*cr+d-1] |= ((ds->entered_items[box*cr+d-1] & 16) << 1) | 16;
7b14a9ec 2928 }
2929 }
2930
2931 /*
1d8e8ad8 2932 * Draw any numbers which need redrawing.
2933 */
2934 for (x = 0; x < cr; x++) {
2935 for (y = 0; y < cr; y++) {
c8266e03 2936 int highlight = 0;
7b14a9ec 2937 digit d = state->grid[y*cr+x];
2938
c8266e03 2939 if (flashtime > 0 &&
2940 (flashtime <= FLASH_TIME/3 ||
2941 flashtime >= FLASH_TIME*2/3))
2942 highlight = 1;
7b14a9ec 2943
2944 /* Highlight active input areas. */
c8266e03 2945 if (x == ui->hx && y == ui->hy)
2946 highlight = ui->hpencil ? 2 : 1;
7b14a9ec 2947
2948 /* Mark obvious errors (ie, numbers which occur more than once
2949 * in a single row, column, or box). */
5d744557 2950 if (d && ((ds->entered_items[x*cr+d-1] & 2) ||
2951 (ds->entered_items[y*cr+d-1] & 8) ||
2952 (ds->entered_items[((x/r)+(y/c)*c)*cr+d-1] & 32)))
7b14a9ec 2953 highlight |= 16;
2954
dafd6cf6 2955 draw_number(dr, ds, state, x, y, highlight);
1d8e8ad8 2956 }
2957 }
2958
2959 /*
2960 * Update the _entire_ grid if necessary.
2961 */
2962 if (!ds->started) {
dafd6cf6 2963 draw_update(dr, 0, 0, SIZE(cr), SIZE(cr));
1d8e8ad8 2964 ds->started = TRUE;
2965 }
2966}
2967
2968static float game_anim_length(game_state *oldstate, game_state *newstate,
e3f21163 2969 int dir, game_ui *ui)
1d8e8ad8 2970{
2971 return 0.0F;
2972}
2973
2974static float game_flash_length(game_state *oldstate, game_state *newstate,
e3f21163 2975 int dir, game_ui *ui)
1d8e8ad8 2976{
2ac6d24e 2977 if (!oldstate->completed && newstate->completed &&
2978 !oldstate->cheated && !newstate->cheated)
1d8e8ad8 2979 return FLASH_TIME;
2980 return 0.0F;
2981}
2982
4d08de49 2983static int game_timing_state(game_state *state, game_ui *ui)
48dcdd62 2984{
2985 return TRUE;
2986}
2987
dafd6cf6 2988static void game_print_size(game_params *params, float *x, float *y)
2989{
2990 int pw, ph;
2991
2992 /*
2993 * I'll use 9mm squares by default. They should be quite big
2994 * for this game, because players will want to jot down no end
2995 * of pencil marks in the squares.
2996 */
2997 game_compute_size(params, 900, &pw, &ph);
2998 *x = pw / 100.0;
2999 *y = ph / 100.0;
3000}
3001
3002static void game_print(drawing *dr, game_state *state, int tilesize)
3003{
3004 int c = state->c, r = state->r, cr = c*r;
3005 int ink = print_mono_colour(dr, 0);
3006 int x, y;
3007
3008 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
3009 game_drawstate ads, *ds = &ads;
4413ef0f 3010 game_set_size(dr, ds, NULL, tilesize);
dafd6cf6 3011
3012 /*
3013 * Border.
3014 */
3015 print_line_width(dr, 3 * TILE_SIZE / 40);
3016 draw_rect_outline(dr, BORDER, BORDER, cr*TILE_SIZE, cr*TILE_SIZE, ink);
3017
3018 /*
3019 * Grid.
3020 */
3021 for (x = 1; x < cr; x++) {
3022 print_line_width(dr, (x % r ? 1 : 3) * TILE_SIZE / 40);
3023 draw_line(dr, BORDER+x*TILE_SIZE, BORDER,
3024 BORDER+x*TILE_SIZE, BORDER+cr*TILE_SIZE, ink);
3025 }
3026 for (y = 1; y < cr; y++) {
3027 print_line_width(dr, (y % c ? 1 : 3) * TILE_SIZE / 40);
3028 draw_line(dr, BORDER, BORDER+y*TILE_SIZE,
3029 BORDER+cr*TILE_SIZE, BORDER+y*TILE_SIZE, ink);
3030 }
3031
3032 /*
3033 * Numbers.
3034 */
3035 for (y = 0; y < cr; y++)
3036 for (x = 0; x < cr; x++)
3037 if (state->grid[y*cr+x]) {
3038 char str[2];
3039 str[1] = '\0';
3040 str[0] = state->grid[y*cr+x] + '0';
3041 if (str[0] > '9')
3042 str[0] += 'a' - ('9'+1);
3043 draw_text(dr, BORDER + x*TILE_SIZE + TILE_SIZE/2,
3044 BORDER + y*TILE_SIZE + TILE_SIZE/2,
3045 FONT_VARIABLE, TILE_SIZE/2,
3046 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, str);
3047 }
3048}
3049
1d8e8ad8 3050#ifdef COMBINED
3051#define thegame solo
3052#endif
3053
3054const struct game thegame = {
750037d7 3055 "Solo", "games.solo", "solo",
1d8e8ad8 3056 default_params,
3057 game_fetch_preset,
3058 decode_params,
3059 encode_params,
3060 free_params,
3061 dup_params,
1d228b10 3062 TRUE, game_configure, custom_params,
1d8e8ad8 3063 validate_params,
1185e3c5 3064 new_game_desc,
1185e3c5 3065 validate_desc,
1d8e8ad8 3066 new_game,
3067 dup_game,
3068 free_game,
2ac6d24e 3069 TRUE, solve_game,
9b4b03d3 3070 TRUE, game_text_format,
1d8e8ad8 3071 new_ui,
3072 free_ui,
ae8290c6 3073 encode_ui,
3074 decode_ui,
07dfb697 3075 game_changed_state,
df11cd4e 3076 interpret_move,
3077 execute_move,
1f3ee4ee 3078 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
1d8e8ad8 3079 game_colours,
3080 game_new_drawstate,
3081 game_free_drawstate,
3082 game_redraw,
3083 game_anim_length,
3084 game_flash_length,
dafd6cf6 3085 TRUE, FALSE, game_print_size, game_print,
ac9f41c4 3086 FALSE, /* wants_statusbar */
48dcdd62 3087 FALSE, game_timing_state,
cb0c7d4a 3088 REQUIRE_RBUTTON | REQUIRE_NUMPAD, /* flags */
1d8e8ad8 3089};
3ddae0ff 3090
3091#ifdef STANDALONE_SOLVER
3092
3ddae0ff 3093int main(int argc, char **argv)
3094{
3095 game_params *p;
3096 game_state *s;
1185e3c5 3097 char *id = NULL, *desc, *err;
7c568a48 3098 int grade = FALSE;
ab362080 3099 int ret;
3ddae0ff 3100
3101 while (--argc > 0) {
3102 char *p = *++argv;
ab362080 3103 if (!strcmp(p, "-v")) {
7c568a48 3104 solver_show_working = TRUE;
7c568a48 3105 } else if (!strcmp(p, "-g")) {
3106 grade = TRUE;
3ddae0ff 3107 } else if (*p == '-') {
8317499a 3108 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3ddae0ff 3109 return 1;
3110 } else {
3111 id = p;
3112 }
3113 }
3114
3115 if (!id) {
ab362080 3116 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3ddae0ff 3117 return 1;
3118 }
3119
1185e3c5 3120 desc = strchr(id, ':');
3121 if (!desc) {
3ddae0ff 3122 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
3123 return 1;
3124 }
1185e3c5 3125 *desc++ = '\0';
3ddae0ff 3126
1733f4ca 3127 p = default_params();
3128 decode_params(p, id);
1185e3c5 3129 err = validate_desc(p, desc);
3ddae0ff 3130 if (err) {
3131 fprintf(stderr, "%s: %s\n", argv[0], err);
3132 return 1;
3133 }
39d682c9 3134 s = new_game(NULL, p, desc);
3ddae0ff 3135
947a07d6 3136 ret = solver(p->c, p->r, s->grid, DIFF_RECURSIVE);
ab362080 3137 if (grade) {
3138 printf("Difficulty rating: %s\n",
3139 ret==DIFF_BLOCK ? "Trivial (blockwise positional elimination only)":
3140 ret==DIFF_SIMPLE ? "Basic (row/column/number elimination required)":
3141 ret==DIFF_INTERSECT ? "Intermediate (intersectional analysis required)":
3142 ret==DIFF_SET ? "Advanced (set elimination required)":
44bf5f6f 3143 ret==DIFF_EXTREME ? "Extreme (complex non-recursive techniques required)":
ab362080 3144 ret==DIFF_RECURSIVE ? "Unreasonable (guesswork and backtracking required)":
3145 ret==DIFF_AMBIGUOUS ? "Ambiguous (multiple solutions exist)":
3146 ret==DIFF_IMPOSSIBLE ? "Impossible (no solution exists)":
3147 "INTERNAL ERROR: unrecognised difficulty code");
3ddae0ff 3148 } else {
ab362080 3149 printf("%s\n", grid_text_format(p->c, p->r, s->grid));
3ddae0ff 3150 }
3151
3ddae0ff 3152 return 0;
3153}
3154
3155#endif