-
Notifications
You must be signed in to change notification settings - Fork 3
/
solo_plus.c
5913 lines (5311 loc) · 191 KB
/
solo_plus.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* solo.c: the number-placing puzzle most popularly known as `Sudoku'.
*
* TODO:
*
* - reports from users are that `Trivial'-mode puzzles are still
* rather hard compared to newspapers' easy ones, so some better
* low-end difficulty grading would be nice
* + it's possible that really easy puzzles always have
* _several_ things you can do, so don't make you hunt too
* hard for the one deduction you can currently make
* + it's also possible that easy puzzles require fewer
* cross-eliminations: perhaps there's a higher incidence of
* things you can deduce by looking only at (say) rows,
* rather than things you have to check both rows and columns
* for
* + but really, what I need to do is find some really easy
* puzzles and _play_ them, to see what's actually easy about
* them
* + while I'm revamping this area, filling in the _last_
* number in a nearly-full row or column should certainly be
* permitted even at the lowest difficulty level.
* + also Owen noticed that `Basic' grids requiring numeric
* elimination are actually very hard, so I wonder if a
* difficulty gradation between that and positional-
* elimination-only might be in order
* + but it's not good to have _too_ many difficulty levels, or
* it'll take too long to randomly generate a given level.
*
* - it might still be nice to do some prioritisation on the
* removal of numbers from the grid
* + one possibility is to try to minimise the maximum number
* of filled squares in any block, which in particular ought
* to enforce never leaving a completely filled block in the
* puzzle as presented.
*
* - alternative interface modes
* + sudoku.com's Windows program has a palette of possible
* entries; you select a palette entry first and then click
* on the square you want it to go in, thus enabling
* mouse-only play. Useful for PDAs! I don't think it's
* actually incompatible with the current highlight-then-type
* approach: you _either_ highlight a palette entry and then
* click, _or_ you highlight a square and then type. At most
* one thing is ever highlighted at a time, so there's no way
* to confuse the two.
* + then again, I don't actually like sudoku.com's interface;
* it's too much like a paint package whereas I prefer to
* think of Solo as a text editor.
* + another PDA-friendly possibility is a drag interface:
* _drag_ numbers from the palette into the grid squares.
* Thought experiments suggest I'd prefer that to the
* sudoku.com approach, but I haven't actually tried it.
*/
/*
* Solo puzzles need to be square overall (since each row and each
* column must contain one of every digit), but they need not be
* subdivided the same way internally. I am going to adopt a
* convention whereby I _always_ refer to `r' as the number of rows
* of _big_ divisions, and `c' as the number of columns of _big_
* divisions. Thus, a 2c by 3r puzzle looks something like this:
*
* 4 5 1 | 2 6 3
* 6 3 2 | 5 4 1
* ------+------ (Of course, you can't subdivide it the other way
* 1 4 5 | 6 3 2 or you'll get clashes; observe that the 4 in the
* 3 2 6 | 4 1 5 top left would conflict with the 4 in the second
* ------+------ box down on the left-hand side.)
* 5 1 4 | 3 2 6
* 2 6 3 | 1 5 4
*
* The need for a strong naming convention should now be clear:
* each small box is two rows of digits by three columns, while the
* overall puzzle has three rows of small boxes by two columns. So
* I will (hopefully) consistently use `r' to denote the number of
* rows _of small boxes_ (here 3), which is also the number of
* columns of digits in each small box; and `c' vice versa (here
* 2).
*
* I'm also going to choose arbitrarily to list c first wherever
* possible: the above is a 2x3 puzzle, not a 3x2 one.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
#ifdef STANDALONE_SOLVER
#include <stdarg.h>
int solver_show_working, solver_recurse_depth;
#endif
#include "puzzles.h"
/*
* To save space, I store digits internally as unsigned char. This
* imposes a hard limit of 255 on the order of the puzzle. Since
* even a 5x5 takes unacceptably long to generate, I don't see this
* as a serious limitation unless something _really_ impressive
* happens in computing technology; but here's a typedef anyway for
* general good practice.
*/
typedef unsigned char digit;
#define ORDER_MAX 255
#define PREFERRED_TILE_SIZE 48
#define TILE_SIZE (ds->tilesize)
#define BORDER (TILE_SIZE / 2)
#define GRIDEXTRA max((TILE_SIZE / 32),1)
#define FLASH_TIME 0.4F
enum { SYMM_NONE, SYMM_ROT2, SYMM_ROT4, SYMM_REF2, SYMM_REF2D, SYMM_REF4,
SYMM_REF4D, SYMM_REF8 };
enum { DIFF_BLOCK,
DIFF_SIMPLE, DIFF_INTERSECT, DIFF_SET, DIFF_EXTREME, DIFF_RECURSIVE,
DIFF_AMBIGUOUS, DIFF_IMPOSSIBLE };
enum { DIFF_KSINGLE, DIFF_KMINMAX, DIFF_KSUMS, DIFF_KINTERSECT };
enum {
COL_BACKGROUND,
COL_XDIAGONALS,
COL_GRID,
COL_CLUE,
COL_USER,
COL_HIGHLIGHT,
COL_NUMHIGHLIGHT,
COL_FILLHIGHLIGHT,
COL_ERROR,
COL_PENCIL,
COL_KILLER,
NCOLOURS
};
/*
* To determine all possible ways to reach a given sum by adding two or
* three numbers from 1..9, each of which occurs exactly once in the sum,
* these arrays contain a list of bitmasks for each sum value, where if
* bit N is set, it means that N occurs in the sum. Each list is
* terminated by a zero if it is shorter than the size of the array.
*/
#define MAX_2SUMS 5
#define MAX_3SUMS 8
#define MAX_4SUMS 12
static unsigned long sum_bits2[18][MAX_2SUMS];
static unsigned long sum_bits3[25][MAX_3SUMS];
static unsigned long sum_bits4[31][MAX_4SUMS];
static int find_sum_bits(unsigned long *array, int idx, int value_left,
int addends_left, int min_addend,
unsigned long bitmask_so_far)
{
int i;
assert(addends_left >= 2);
for (i = min_addend; i < value_left; i++) {
unsigned long new_bitmask = bitmask_so_far | (1L << i);
assert(bitmask_so_far != new_bitmask);
if (addends_left == 2) {
int j = value_left - i;
if (j <= i)
break;
if (j > 9)
continue;
array[idx++] = new_bitmask | (1L << j);
} else
idx = find_sum_bits(array, idx, value_left - i,
addends_left - 1, i + 1,
new_bitmask);
}
return idx;
}
static void precompute_sum_bits(void)
{
int i;
for (i = 3; i < 31; i++) {
int j;
if (i < 18) {
j = find_sum_bits(sum_bits2[i], 0, i, 2, 1, 0);
assert (j <= MAX_2SUMS);
if (j < MAX_2SUMS)
sum_bits2[i][j] = 0;
}
if (i < 25) {
j = find_sum_bits(sum_bits3[i], 0, i, 3, 1, 0);
assert (j <= MAX_3SUMS);
if (j < MAX_3SUMS)
sum_bits3[i][j] = 0;
}
j = find_sum_bits(sum_bits4[i], 0, i, 4, 1, 0);
assert (j <= MAX_4SUMS);
if (j < MAX_4SUMS)
sum_bits4[i][j] = 0;
}
}
struct game_params {
/*
* For a square puzzle, `c' and `r' indicate the puzzle
* parameters as described above.
*
* A jigsaw-style puzzle is indicated by r==1, in which case c
* can be whatever it likes (there is no constraint on
* compositeness - a 7x7 jigsaw sudoku makes perfect sense).
*/
int c, r, symm, diff, kdiff;
bool xtype; /* require all digits in X-diagonals */
bool killer;
bool manual;
};
struct block_structure {
int refcount;
/*
* For text formatting, we do need c and r here.
*/
int c, r, area;
/*
* For any square index, whichblock[i] gives its block index.
*
* For 0 <= b,i < cr, blocks[b][i] gives the index of the ith
* square in block b. nr_squares[b] gives the number of squares
* in block b (also the number of valid elements in blocks[b]).
*
* blocks_data holds the data pointed to by blocks.
*
* nr_squares may be NULL for block structures where all blocks are
* the same size.
*/
int *whichblock, **blocks, *nr_squares, *blocks_data;
int nr_blocks, max_nr_squares;
#ifdef STANDALONE_SOLVER
/*
* Textual descriptions of each block. For normal Sudoku these
* are of the form "(1,3)"; for jigsaw they are "starting at
* (5,7)". So the sensible usage in both cases is to say
* "elimination within block %s" with one of these strings.
*
* Only blocknames itself needs individually freeing; it's all
* one block.
*/
char **blocknames;
#endif
};
struct game_state {
/*
* For historical reasons, I use `cr' to denote the overall
* width/height of the puzzle. It was a natural notation when
* all puzzles were divided into blocks in a grid, but doesn't
* really make much sense given jigsaw puzzles. However, the
* obvious `n' is heavily used in the solver to describe the
* index of a number being placed, so `cr' will have to stay.
*/
int cr;
struct block_structure *blocks;
struct block_structure *kblocks; /* Blocks for killer puzzles. */
bool xtype, killer, manual;
digit *grid, *kgrid;
bool *pencil; /* c*r*c*r elements */
bool *immutable; /* marks which digits are clues */
bool completed, cheated, fixed;
};
static midend *current_midend;
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->c = ret->r = 3;
ret->xtype = false;
ret->killer = false;
ret->manual = false;
ret->symm = SYMM_ROT2; /* a plausible default */
ret->diff = DIFF_BLOCK; /* so is this */
ret->kdiff = DIFF_KINTERSECT; /* so is this */
return ret;
}
static void free_params(game_params *params)
{
sfree(params);
}
static game_params *dup_params(const game_params *params)
{
game_params *ret = snew(game_params);
*ret = *params; /* structure copy */
return ret;
}
static bool game_fetch_preset(int i, char **name, game_params **params)
{
static struct {
const char *title;
game_params params;
} const presets[] = {
{ "3x3 Manual", { 3, 3, SYMM_NONE, DIFF_BLOCK, DIFF_KMINMAX, false, false, true } },
{ "2x2 Trivial", { 2, 2, SYMM_ROT2, DIFF_BLOCK, DIFF_KMINMAX, false, false, false } },
{ "2x3 Basic", { 2, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, false, false, false } },
{ "3x3 Trivial", { 3, 3, SYMM_ROT2, DIFF_BLOCK, DIFF_KMINMAX, false, false, false } },
{ "3x3 Basic", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, false, false, false } },
{ "3x3 Basic X", { 3, 3, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, true, false, false } },
{ "3x3 Intermediate", { 3, 3, SYMM_ROT2, DIFF_INTERSECT, DIFF_KMINMAX, false, false, false } },
{ "3x3 Advanced", { 3, 3, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, false, false, false } },
{ "3x3 Advanced X", { 3, 3, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, true, false, false } },
{ "3x3 Extreme", { 3, 3, SYMM_ROT2, DIFF_EXTREME, DIFF_KMINMAX, false, false, false } },
{ "3x3 Unreasonable", { 3, 3, SYMM_ROT2, DIFF_RECURSIVE, DIFF_KMINMAX, false, false, false } },
{ "3x3 Killer", { 3, 3, SYMM_NONE, DIFF_BLOCK, DIFF_KINTERSECT, false, true, false } },
{ "9 Jigsaw Basic", { 9, 1, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, false, false, false } },
{ "9 Jigsaw Basic X", { 9, 1, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, true, false, false } },
{ "9 Jigsaw Advanced", { 9, 1, SYMM_ROT2, DIFF_SET, DIFF_KMINMAX, false, false, false } },
#ifndef SLOW_SYSTEM
{ "3x4 Basic", { 3, 4, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, false, false, false } },
{ "4x4 Basic", { 4, 4, SYMM_ROT2, DIFF_SIMPLE, DIFF_KMINMAX, false, false, false } },
#endif
};
if (i < 0 || i >= lenof(presets))
return false;
*name = dupstr(presets[i].title);
*params = dup_params(&presets[i].params);
return true;
}
static void decode_params(game_params *ret, char const *string)
{
bool seen_r = false;
ret->c = ret->r = atoi(string);
ret->xtype = false;
ret->killer = false;
while (*string && isdigit((unsigned char)*string)) string++;
if (*string == 'x') {
string++;
ret->r = atoi(string);
seen_r = true;
while (*string && isdigit((unsigned char)*string)) string++;
}
while (*string) {
if (*string == 'j') {
string++;
if (seen_r)
ret->c *= ret->r;
ret->r = 1;
} else if (*string == 'x') {
string++;
ret->xtype = true;
} else if (*string == 'k') {
string++;
ret->killer = true;
} else if (*string == 'y') {
string++;
ret->manual = true;
} else if (*string == 'r' || *string == 'm' || *string == 'a') {
int sn, sc;
bool sd;
sc = *string++;
if (sc == 'm' && *string == 'd') {
sd = true;
string++;
} else {
sd = false;
}
sn = atoi(string);
while (*string && isdigit((unsigned char)*string)) string++;
if (sc == 'm' && sn == 8)
ret->symm = SYMM_REF8;
if (sc == 'm' && sn == 4)
ret->symm = sd ? SYMM_REF4D : SYMM_REF4;
if (sc == 'm' && sn == 2)
ret->symm = sd ? SYMM_REF2D : SYMM_REF2;
if (sc == 'r' && sn == 4)
ret->symm = SYMM_ROT4;
if (sc == 'r' && sn == 2)
ret->symm = SYMM_ROT2;
if (sc == 'a')
ret->symm = SYMM_NONE;
} else if (*string == 'd') {
string++;
if (*string == 't') /* trivial */
string++, ret->diff = DIFF_BLOCK;
else if (*string == 'b') /* basic */
string++, ret->diff = DIFF_SIMPLE;
else if (*string == 'i') /* intermediate */
string++, ret->diff = DIFF_INTERSECT;
else if (*string == 'a') /* advanced */
string++, ret->diff = DIFF_SET;
else if (*string == 'e') /* extreme */
string++, ret->diff = DIFF_EXTREME;
else if (*string == 'u') /* unreasonable */
string++, ret->diff = DIFF_RECURSIVE;
} else
string++; /* eat unknown character */
}
}
static char *encode_params(const game_params *params, bool full)
{
char str[80];
if (params->r > 1)
sprintf(str, "%dx%d", params->c, params->r);
else
sprintf(str, "%dj", params->c);
if (params->xtype)
strcat(str, "x");
if (params->killer)
strcat(str, "k");
if (params->manual)
strcat(str, "y");
if (full) {
switch (params->symm) {
case SYMM_REF8: strcat(str, "m8"); break;
case SYMM_REF4: strcat(str, "m4"); break;
case SYMM_REF4D: strcat(str, "md4"); break;
case SYMM_REF2: strcat(str, "m2"); break;
case SYMM_REF2D: strcat(str, "md2"); break;
case SYMM_ROT4: strcat(str, "r4"); break;
/* case SYMM_ROT2: strcat(str, "r2"); break; [default] */
case SYMM_NONE: strcat(str, "a"); break;
}
switch (params->diff) {
/* case DIFF_BLOCK: strcat(str, "dt"); break; [default] */
case DIFF_SIMPLE: strcat(str, "db"); break;
case DIFF_INTERSECT: strcat(str, "di"); break;
case DIFF_SET: strcat(str, "da"); break;
case DIFF_EXTREME: strcat(str, "de"); break;
case DIFF_RECURSIVE: strcat(str, "du"); break;
}
}
return dupstr(str);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(9, config_item);
ret[0].name = "Columns of sub-blocks";
ret[0].type = C_STRING;
sprintf(buf, "%d", params->c);
ret[0].u.string.sval = dupstr(buf);
ret[1].name = "Rows of sub-blocks";
ret[1].type = C_STRING;
sprintf(buf, "%d", params->r);
ret[1].u.string.sval = dupstr(buf);
ret[2].name = "\"X\" (require every number in each main diagonal)";
ret[2].type = C_BOOLEAN;
ret[2].u.boolean.bval = params->xtype;
ret[3].name = "Jigsaw (irregularly shaped sub-blocks)";
ret[3].type = C_BOOLEAN;
ret[3].u.boolean.bval = (params->r == 1);
ret[4].name = "Killer (digit sums)";
ret[4].type = C_BOOLEAN;
ret[4].u.boolean.bval = params->killer;
ret[5].name = "Manual (fillable empty grid)";
ret[5].type = C_BOOLEAN;
ret[5].u.boolean.bval = params->manual;
ret[6].name = "Symmetry";
ret[6].type = C_CHOICES;
ret[6].u.choices.choicenames = ":None:2-way rotation:4-way rotation:2-way mirror:"
"2-way diagonal mirror:4-way mirror:4-way diagonal mirror:"
"8-way mirror";
ret[6].u.choices.selected = params->symm;
ret[7].name = "Difficulty";
ret[7].type = C_CHOICES;
ret[7].u.choices.choicenames = ":Trivial:Basic:Intermediate:Advanced:Extreme:Unreasonable";
ret[7].u.choices.selected = params->diff;
ret[8].name = NULL;
ret[8].type = C_END;
return ret;
}
static game_params *custom_params(const config_item *cfg)
{
game_params *ret = snew(game_params);
ret->c = atoi(cfg[0].u.string.sval);
ret->r = atoi(cfg[1].u.string.sval);
ret->xtype = cfg[2].u.boolean.bval;
if (cfg[3].u.boolean.bval) {
ret->c *= ret->r;
ret->r = 1;
}
ret->killer = cfg[4].u.boolean.bval;
ret->manual = cfg[5].u.boolean.bval;
ret->symm = cfg[6].u.choices.selected;
ret->diff = cfg[7].u.choices.selected;
ret->kdiff = DIFF_KINTERSECT;
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
if (params->manual && (params->c != 3 || params->r != 3 || params->xtype || params->killer))
return "Manual mode only for regular 3x3 grids";
if (params->c < 2)
return "Both dimensions must be at least 2";
if (params->c > ORDER_MAX || params->r > ORDER_MAX)
return "Dimensions greater than "STR(ORDER_MAX)" are not supported";
if ((params->c * params->r) > 31)
return "Unable to support more than 31 distinct symbols in a puzzle";
if (params->killer && params->c * params->r > 9)
return "Killer puzzle dimensions must be smaller than 10";
if (params->xtype && params->c * params->r < 4)
return "X-type puzzle dimensions must be larger than 3";
return NULL;
}
/*
* ----------------------------------------------------------------------
* Block structure functions.
*/
static struct block_structure *alloc_block_structure(int c, int r, int area,
int max_nr_squares,
int nr_blocks)
{
int i;
struct block_structure *b = snew(struct block_structure);
b->refcount = 1;
b->nr_blocks = nr_blocks;
b->max_nr_squares = max_nr_squares;
b->c = c; b->r = r; b->area = area;
b->whichblock = snewn(area, int);
b->blocks_data = snewn(nr_blocks * max_nr_squares, int);
b->blocks = snewn(nr_blocks, int *);
b->nr_squares = snewn(nr_blocks, int);
for (i = 0; i < nr_blocks; i++)
b->blocks[i] = b->blocks_data + i*max_nr_squares;
#ifdef STANDALONE_SOLVER
b->blocknames = (char **)smalloc(c*r*(sizeof(char *)+80));
for (i = 0; i < c * r; i++)
b->blocknames[i] = NULL;
#endif
return b;
}
static void free_block_structure(struct block_structure *b)
{
if (--b->refcount == 0) {
sfree(b->whichblock);
sfree(b->blocks);
sfree(b->blocks_data);
#ifdef STANDALONE_SOLVER
sfree(b->blocknames);
#endif
sfree(b->nr_squares);
sfree(b);
}
}
static struct block_structure *dup_block_structure(struct block_structure *b)
{
struct block_structure *nb;
int i;
nb = alloc_block_structure(b->c, b->r, b->area, b->max_nr_squares,
b->nr_blocks);
memcpy(nb->nr_squares, b->nr_squares, b->nr_blocks * sizeof *b->nr_squares);
memcpy(nb->whichblock, b->whichblock, b->area * sizeof *b->whichblock);
memcpy(nb->blocks_data, b->blocks_data,
b->nr_blocks * b->max_nr_squares * sizeof *b->blocks_data);
for (i = 0; i < b->nr_blocks; i++)
nb->blocks[i] = nb->blocks_data + i*nb->max_nr_squares;
#ifdef STANDALONE_SOLVER
memcpy(nb->blocknames, b->blocknames, b->c * b->r *(sizeof(char *)+80));
{
int i;
for (i = 0; i < b->c * b->r; i++)
if (b->blocknames[i] == NULL)
nb->blocknames[i] = NULL;
else
nb->blocknames[i] = ((char *)nb->blocknames) + (b->blocknames[i] - (char *)b->blocknames);
}
#endif
return nb;
}
static void split_block(struct block_structure *b, int *squares, int nr_squares)
{
int i, j;
int previous_block = b->whichblock[squares[0]];
int newblock = b->nr_blocks;
assert(b->max_nr_squares >= nr_squares);
assert(b->nr_squares[previous_block] > nr_squares);
b->nr_blocks++;
b->blocks_data = sresize(b->blocks_data,
b->nr_blocks * b->max_nr_squares, int);
b->nr_squares = sresize(b->nr_squares, b->nr_blocks, int);
sfree(b->blocks);
b->blocks = snewn(b->nr_blocks, int *);
for (i = 0; i < b->nr_blocks; i++)
b->blocks[i] = b->blocks_data + i*b->max_nr_squares;
for (i = 0; i < nr_squares; i++) {
assert(b->whichblock[squares[i]] == previous_block);
b->whichblock[squares[i]] = newblock;
b->blocks[newblock][i] = squares[i];
}
for (i = j = 0; i < b->nr_squares[previous_block]; i++) {
int k;
int sq = b->blocks[previous_block][i];
for (k = 0; k < nr_squares; k++)
if (squares[k] == sq)
break;
if (k == nr_squares)
b->blocks[previous_block][j++] = sq;
}
b->nr_squares[previous_block] -= nr_squares;
b->nr_squares[newblock] = nr_squares;
}
static void remove_from_block(struct block_structure *blocks, int b, int n)
{
int i, j;
blocks->whichblock[n] = -1;
for (i = j = 0; i < blocks->nr_squares[b]; i++)
if (blocks->blocks[b][i] != n)
blocks->blocks[b][j++] = blocks->blocks[b][i];
assert(j+1 == i);
blocks->nr_squares[b]--;
}
/* ----------------------------------------------------------------------
* Solver.
*
* This solver is used for two purposes:
* + to check solubility of a grid as we gradually remove numbers
* from it
* + to solve an externally generated puzzle when the user selects
* `Solve'.
*
* It supports a variety of specific modes of reasoning. By
* enabling or disabling subsets of these modes we can arrange a
* range of difficulty levels.
*/
/*
* Modes of reasoning currently supported:
*
* - Positional elimination: a number must go in a particular
* square because all the other empty squares in a given
* row/col/blk are ruled out.
*
* - Killer minmax elimination: for killer-type puzzles, a number
* is impossible if choosing it would cause the sum in a killer
* region to be guaranteed to be too large or too small.
*
* - Numeric elimination: a square must have a particular number
* in because all the other numbers that could go in it are
* ruled out.
*
* - Intersectional analysis: given two domains which overlap
* (hence one must be a block, and the other can be a row or
* col), if the possible locations for a particular number in
* one of the domains can be narrowed down to the overlap, then
* that number can be ruled out everywhere but the overlap in
* the other domain too.
*
* - Set elimination: if there is a subset of the empty squares
* within a domain such that the union of the possible numbers
* in that subset has the same size as the subset itself, then
* those numbers can be ruled out everywhere else in the domain.
* (For example, if there are five empty squares and the
* possible numbers in each are 12, 23, 13, 134 and 1345, then
* the first three empty squares form such a subset: the numbers
* 1, 2 and 3 _must_ be in those three squares in some
* permutation, and hence we can deduce none of them can be in
* the fourth or fifth squares.)
* + You can also see this the other way round, concentrating
* on numbers rather than squares: if there is a subset of
* the unplaced numbers within a domain such that the union
* of all their possible positions has the same size as the
* subset itself, then all other numbers can be ruled out for
* those positions. However, it turns out that this is
* exactly equivalent to the first formulation at all times:
* there is a 1-1 correspondence between suitable subsets of
* the unplaced numbers and suitable subsets of the unfilled
* places, found by taking the _complement_ of the union of
* the numbers' possible positions (or the spaces' possible
* contents).
*
* - Forcing chains (see comment for solver_forcing().)
*
* - Recursion. If all else fails, we pick one of the currently
* most constrained empty squares and take a random guess at its
* contents, then continue solving on that basis and see if we
* get any further.
*/
struct solver_usage {
int cr;
struct block_structure *blocks, *kblocks, *extra_cages;
/*
* We set up a cubic array, indexed by x, y and digit; each
* element of this array is true or false according to whether
* or not that digit _could_ in principle go in that position.
*
* The way to index this array is cube[(y*cr+x)*cr+n-1]; there
* are macros below to help with this.
*/
bool *cube;
/*
* This is the grid in which we write down our final
* deductions. y-coordinates in here are _not_ transformed.
*/
digit *grid;
/*
* For killer-type puzzles, kclues holds the secondary clue for
* each cage. For derived cages, the clue is in extra_clues.
*/
digit *kclues, *extra_clues;
/*
* Now we keep track, at a slightly higher level, of what we
* have yet to work out, to prevent doing the same deduction
* many times.
*/
/* row[y*cr+n-1] true if digit n has been placed in row y */
bool *row;
/* col[x*cr+n-1] true if digit n has been placed in row x */
bool *col;
/* blk[i*cr+n-1] true if digit n has been placed in block i */
bool *blk;
/* diag[i*cr+n-1] true if digit n has been placed in diagonal i */
bool *diag; /* diag 0 is \, 1 is / */
int *regions;
int nr_regions;
int **sq2region;
};
#define cubepos2(xy,n) ((xy)*usage->cr+(n)-1)
#define cubepos(x,y,n) cubepos2((y)*usage->cr+(x),n)
#define cube(x,y,n) (usage->cube[cubepos(x,y,n)])
#define cube2(xy,n) (usage->cube[cubepos2(xy,n)])
#define ondiag0(xy) ((xy) % (cr+1) == 0)
#define ondiag1(xy) ((xy) % (cr-1) == 0 && (xy) > 0 && (xy) < cr*cr-1)
#define diag0(i) ((i) * (cr+1))
#define diag1(i) ((i+1) * (cr-1))
/*
* Function called when we are certain that a particular square has
* a particular number in it. The y-coordinate passed in here is
* transformed.
*/
static void solver_place(struct solver_usage *usage, int x, int y, int n)
{
int cr = usage->cr;
int sqindex = y*cr+x;
int i, bi;
assert(cube(x,y,n));
/*
* Rule out all other numbers in this square.
*/
for (i = 1; i <= cr; i++)
if (i != n)
cube(x,y,i) = false;
/*
* Rule out this number in all other positions in the row.
*/
for (i = 0; i < cr; i++)
if (i != y)
cube(x,i,n) = false;
/*
* Rule out this number in all other positions in the column.
*/
for (i = 0; i < cr; i++)
if (i != x)
cube(i,y,n) = false;
/*
* Rule out this number in all other positions in the block.
*/
bi = usage->blocks->whichblock[sqindex];
for (i = 0; i < cr; i++) {
int bp = usage->blocks->blocks[bi][i];
if (bp != sqindex)
cube2(bp,n) = false;
}
/*
* Enter the number in the result grid.
*/
usage->grid[sqindex] = n;
/*
* Cross out this number from the list of numbers left to place
* in its row, its column and its block.
*/
usage->row[y*cr+n-1] = usage->col[x*cr+n-1] =
usage->blk[bi*cr+n-1] = true;
if (usage->diag) {
if (ondiag0(sqindex)) {
for (i = 0; i < cr; i++)
if (diag0(i) != sqindex)
cube2(diag0(i),n) = false;
usage->diag[n-1] = true;
}
if (ondiag1(sqindex)) {
for (i = 0; i < cr; i++)
if (diag1(i) != sqindex)
cube2(diag1(i),n) = false;
usage->diag[cr+n-1] = true;
}
}
}
#if defined STANDALONE_SOLVER && defined __GNUC__
/*
* Forward-declare the functions taking printf-like format arguments
* with __attribute__((format)) so as to ensure the argument syntax
* gets debugged.
*/
struct solver_scratch;
static int solver_elim(struct solver_usage *usage, int *indices,
const char *fmt, ...)
__attribute__((format(printf,3,4)));
static int solver_intersect(struct solver_usage *usage,
int *indices1, int *indices2, const char *fmt, ...)
__attribute__((format(printf,4,5)));
static int solver_set(struct solver_usage *usage,
struct solver_scratch *scratch,
int *indices, const char *fmt, ...)
__attribute__((format(printf,4,5)));
#endif
static int solver_elim(struct solver_usage *usage, int *indices
#ifdef STANDALONE_SOLVER
, const char *fmt, ...
#endif
)
{
int cr = usage->cr;
int fpos, m, i;
/*
* Count the number of set bits within this section of the
* cube.
*/
m = 0;
fpos = -1;
for (i = 0; i < cr; i++)
if (usage->cube[indices[i]]) {
fpos = indices[i];
m++;
}
if (m == 1) {
int x, y, n;
assert(fpos >= 0);
n = 1 + fpos % cr;
x = fpos / cr;
y = x / cr;
x %= cr;
if (!usage->grid[y*cr+x]) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
va_list ap;
printf("%*s", solver_recurse_depth*4, "");
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
printf(":\n%*s placing %d at (%d,%d)\n",
solver_recurse_depth*4, "", n, 1+x, 1+y);
}
#endif
solver_place(usage, x, y, n);
return +1;
}
} else if (m == 0) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
va_list ap;
printf("%*s", solver_recurse_depth*4, "");
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
printf(":\n%*s no possibilities available\n",
solver_recurse_depth*4, "");
}
#endif
return -1;
}
return 0;
}
static int solver_intersect(struct solver_usage *usage,
int *indices1, int *indices2
#ifdef STANDALONE_SOLVER
, const char *fmt, ...
#endif
)
{
int cr = usage->cr;
int ret, i, j;
/*
* Loop over the first domain and see if there's any set bit
* not also in the second.
*/
for (i = j = 0; i < cr; i++) {
int p = indices1[i];
while (j < cr && indices2[j] < p)
j++;
if (usage->cube[p]) {
if (j < cr && indices2[j] == p)
continue; /* both domains contain this index */
else
return 0; /* there is, so we can't deduce */
}
}
/*
* We have determined that all set bits in the first domain are
* within its overlap with the second. So loop over the second
* domain and remove all set bits that aren't also in that
* overlap; return +1 iff we actually _did_ anything.
*/
ret = 0;
for (i = j = 0; i < cr; i++) {
int p = indices2[i];
while (j < cr && indices1[j] < p)
j++;
if (usage->cube[p] && (j >= cr || indices1[j] != p)) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
int px, py, pn;
if (!ret) {
va_list ap;
printf("%*s", solver_recurse_depth*4, "");
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
printf(":\n");
}
pn = 1 + p % cr;
px = p / cr;
py = px / cr;
px %= cr;
printf("%*s ruling out %d at (%d,%d)\n",
solver_recurse_depth*4, "", pn, 1+px, 1+py);
}
#endif
ret = +1; /* we did something */
usage->cube[p] = false;
}
}
return ret;
}
struct solver_scratch {
unsigned char *grid, *rowidx, *colidx, *set;
int *neighbours, *bfsqueue;