-
Notifications
You must be signed in to change notification settings - Fork 0
/
keen.c
2654 lines (2330 loc) · 68.8 KB
/
keen.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
/*
* keen.c: an implementation of the Times's 'KenKen' puzzle, and
* also of Nikoli's very similar 'Inshi No Heya' puzzle.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#ifdef NO_TGMATH_H
# include <math.h>
#else
# include <tgmath.h>
#endif
#include "puzzles.h"
#include "latin.h"
/*
* Difficulty levels. I do some macro ickery here to ensure that my
* enum and the various forms of my name list always match up.
*/
#define DIFFLIST(A) \
A(EASY,Easy,solver_easy,e) \
A(NORMAL,Normal,solver_normal,n) \
A(HARD,Hard,solver_hard,h) \
A(EXTREME,Extreme,NULL,x) \
A(UNREASONABLE,Unreasonable,NULL,u)
#define ENUM(upper,title,func,lower) DIFF_ ## upper,
#define TITLE(upper,title,func,lower) #title,
#define ENCODE(upper,title,func,lower) #lower
#define CONFIG(upper,title,func,lower) ":" #title
enum { DIFFLIST(ENUM) DIFFCOUNT };
static char const *const keen_diffnames[] = { DIFFLIST(TITLE) };
static char const keen_diffchars[] = DIFFLIST(ENCODE);
#define DIFFCONFIG DIFFLIST(CONFIG)
/*
* Clue notation. Important here that ADD and MUL come before SUB
* and DIV, and that DIV comes last.
*/
#define C_ADD 0x00000000L
#define C_MUL 0x20000000L
#define C_SUB 0x40000000L
#define C_DIV 0x60000000L
#define CMASK 0x60000000L
#define CUNIT 0x20000000L
/*
* Maximum size of any clue block. Very large ones are annoying in UI
* terms (if they're multiplicative you end up with too many digits to
* fit in the square) and also in solver terms (too many possibilities
* to iterate over).
*/
#define MAXBLK 6
enum {
COL_BACKGROUND,
COL_GRID,
COL_USER,
COL_HIGHLIGHT,
COL_ERROR,
COL_PENCIL,
NCOLOURS
};
struct game_params {
int w, diff;
bool multiplication_only;
};
struct clues {
int refcount;
int w;
DSF *dsf;
long *clues;
};
struct game_state {
game_params par;
struct clues *clues;
digit *grid;
int *pencil; /* bitmaps using bits 1<<1..1<<n */
bool completed, cheated;
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->w = 6;
ret->diff = DIFF_NORMAL;
ret->multiplication_only = false;
return ret;
}
static const struct game_params keen_presets[] = {
{ 4, DIFF_EASY, false },
{ 5, DIFF_EASY, false },
{ 5, DIFF_EASY, true },
{ 6, DIFF_EASY, false },
{ 6, DIFF_NORMAL, false },
{ 6, DIFF_NORMAL, true },
{ 6, DIFF_HARD, false },
{ 6, DIFF_EXTREME, false },
{ 6, DIFF_UNREASONABLE, false },
{ 9, DIFF_NORMAL, false },
};
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char buf[80];
if (i < 0 || i >= lenof(keen_presets))
return false;
ret = snew(game_params);
*ret = keen_presets[i]; /* structure copy */
sprintf(buf, "%dx%d %s%s", ret->w, ret->w, keen_diffnames[ret->diff],
ret->multiplication_only ? ", multiplication only" : "");
*name = dupstr(buf);
*params = ret;
return true;
}
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 void decode_params(game_params *params, char const *string)
{
char const *p = string;
params->w = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
if (*p == 'd') {
int i;
p++;
params->diff = DIFFCOUNT+1; /* ...which is invalid */
if (*p) {
for (i = 0; i < DIFFCOUNT; i++) {
if (*p == keen_diffchars[i])
params->diff = i;
}
p++;
}
}
if (*p == 'm') {
p++;
params->multiplication_only = true;
}
}
static char *encode_params(const game_params *params, bool full)
{
char ret[80];
sprintf(ret, "%d", params->w);
if (full)
sprintf(ret + strlen(ret), "d%c%s", keen_diffchars[params->diff],
params->multiplication_only ? "m" : "");
return dupstr(ret);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(4, config_item);
ret[0].name = "Grid size";
ret[0].type = C_STRING;
sprintf(buf, "%d", params->w);
ret[0].u.string.sval = dupstr(buf);
ret[1].name = "Difficulty";
ret[1].type = C_CHOICES;
ret[1].u.choices.choicenames = DIFFCONFIG;
ret[1].u.choices.selected = params->diff;
ret[2].name = "Multiplication only";
ret[2].type = C_BOOLEAN;
ret[2].u.boolean.bval = params->multiplication_only;
ret[3].name = NULL;
ret[3].type = C_END;
return ret;
}
static game_params *custom_params(const config_item *cfg)
{
game_params *ret = snew(game_params);
ret->w = atoi(cfg[0].u.string.sval);
ret->diff = cfg[1].u.choices.selected;
ret->multiplication_only = cfg[2].u.boolean.bval;
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
if (params->w < 3 || params->w > 9)
return "Grid size must be between 3 and 9";
if (params->diff >= DIFFCOUNT)
return "Unknown difficulty rating";
return NULL;
}
/* ----------------------------------------------------------------------
* Solver.
*/
struct solver_ctx {
int w, diff;
int nboxes;
int *boxes, *boxlist, *whichbox;
long *clues;
digit *soln;
digit *dscratch;
int *iscratch;
};
static void solver_clue_candidate(struct solver_ctx *ctx, int diff, int box)
{
int w = ctx->w;
int n = ctx->boxes[box+1] - ctx->boxes[box];
int j;
/*
* This function is called from the main clue-based solver
* routine when we discover a candidate layout for a given clue
* box consistent with everything we currently know about the
* digit constraints in that box. We expect to find the digits
* of the candidate layout in ctx->dscratch, and we update
* ctx->iscratch as appropriate.
*
* The contents of ctx->iscratch are completely different
* depending on whether diff == DIFF_HARD or not. This function
* uses iscratch completely differently between the two cases, and
* the code in solver_common() which consumes the result must
* likewise have an if statement with completely different
* branches for the two cases.
*
* In DIFF_EASY and DIFF_NORMAL modes, the valid entries in
* ctx->iscratch are 0,...,n-1, and each of those entries
* ctx->iscratch[i] gives a bitmap of the possible digits in the
* ith square of the clue box currently under consideration. So
* each entry of iscratch starts off as an empty bitmap, and we
* set bits in it as possible layouts for the clue box are
* considered (and the difference between DIFF_EASY and
* DIFF_NORMAL is just that in DIFF_EASY mode we deliberately set
* more bits than absolutely necessary, hence restricting our own
* knowledge).
*
* But in DIFF_HARD mode, the valid entries are 0,...,2*w-1 (at
* least outside *this* function - inside this function, we also
* use 2*w,...,4*w-1 as scratch space in the loop below); the
* first w of those give the possible digits in the intersection
* of the current clue box with each column of the puzzle, and the
* next w do the same for each row. In this mode, each iscratch
* entry starts off as a _full_ bitmap, and in this function we
* _clear_ bits for digits that are absent from a given row or
* column in each candidate layout, so that the only bits which
* remain set are those for digits which have to appear in a given
* row/column no matter how the clue box is laid out.
*/
if (diff == DIFF_EASY) {
unsigned mask = 0;
/*
* Easy-mode clue deductions: we do not record information
* about which squares take which values, so we amalgamate
* all the values in dscratch and OR them all into
* everywhere.
*/
for (j = 0; j < n; j++)
mask |= 1 << ctx->dscratch[j];
for (j = 0; j < n; j++)
ctx->iscratch[j] |= mask;
} else if (diff == DIFF_NORMAL) {
/*
* Normal-mode deductions: we process the information in
* dscratch in the obvious way.
*/
for (j = 0; j < n; j++)
ctx->iscratch[j] |= 1 << ctx->dscratch[j];
} else if (diff == DIFF_HARD) {
/*
* Hard-mode deductions: instead of ruling things out
* _inside_ the clue box, we look for numbers which occur in
* a given row or column in all candidate layouts, and rule
* them out of all squares in that row or column that
* _aren't_ part of this clue box.
*/
int *sq = ctx->boxlist + ctx->boxes[box];
for (j = 0; j < 2*w; j++)
ctx->iscratch[2*w+j] = 0;
for (j = 0; j < n; j++) {
int x = sq[j] / w, y = sq[j] % w;
ctx->iscratch[2*w+x] |= 1 << ctx->dscratch[j];
ctx->iscratch[3*w+y] |= 1 << ctx->dscratch[j];
}
for (j = 0; j < 2*w; j++)
ctx->iscratch[j] &= ctx->iscratch[2*w+j];
}
}
static int solver_common(struct latin_solver *solver, void *vctx, int diff)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
int w = ctx->w;
int box, i, j, k;
int ret = 0, total;
/*
* Iterate over each clue box and deduce what we can.
*/
for (box = 0; box < ctx->nboxes; box++) {
int *sq = ctx->boxlist + ctx->boxes[box];
int n = ctx->boxes[box+1] - ctx->boxes[box];
long value = ctx->clues[box] & ~CMASK;
long op = ctx->clues[box] & CMASK;
/*
* Initialise ctx->iscratch for this clue box. At different
* difficulty levels we must initialise a different amount of
* it to different things; see the comments in
* solver_clue_candidate explaining what each version does.
*/
if (diff == DIFF_HARD) {
for (i = 0; i < 2*w; i++)
ctx->iscratch[i] = (1 << (w+1)) - (1 << 1);
} else {
for (i = 0; i < n; i++)
ctx->iscratch[i] = 0;
}
switch (op) {
case C_SUB:
case C_DIV:
/*
* These two clue types must always apply to a box of
* area 2. Also, the two digits in these boxes can never
* be the same (because any domino must have its two
* squares in either the same row or the same column).
* So we simply iterate over all possibilities for the
* two squares (both ways round), rule out any which are
* inconsistent with the digit constraints we already
* have, and update the digit constraints with any new
* information thus garnered.
*/
assert(n == 2);
for (i = 1; i <= w; i++) {
j = (op == C_SUB ? i + value : i * value);
if (j > w) break;
/* (i,j) is a valid digit pair. Try it both ways round. */
if (solver->cube[sq[0]*w+i-1] &&
solver->cube[sq[1]*w+j-1]) {
ctx->dscratch[0] = i;
ctx->dscratch[1] = j;
solver_clue_candidate(ctx, diff, box);
}
if (solver->cube[sq[0]*w+j-1] &&
solver->cube[sq[1]*w+i-1]) {
ctx->dscratch[0] = j;
ctx->dscratch[1] = i;
solver_clue_candidate(ctx, diff, box);
}
}
break;
case C_ADD:
case C_MUL:
/*
* For these clue types, I have no alternative but to go
* through all possible number combinations.
*
* Instead of a tedious physical recursion, I iterate in
* the scratch array through all possibilities. At any
* given moment, i indexes the element of the box that
* will next be incremented.
*/
i = 0;
ctx->dscratch[i] = 0;
total = value; /* start with the identity */
while (1) {
if (i < n) {
/*
* Find the next valid value for cell i.
*/
for (j = ctx->dscratch[i] + 1; j <= w; j++) {
if (op == C_ADD ? (total < j) : (total % j != 0))
continue; /* this one won't fit */
if (!solver->cube[sq[i]*w+j-1])
continue; /* this one is ruled out already */
for (k = 0; k < i; k++)
if (ctx->dscratch[k] == j &&
(sq[k] % w == sq[i] % w ||
sq[k] / w == sq[i] / w))
break; /* clashes with another row/col */
if (k < i)
continue;
/* Found one. */
break;
}
if (j > w) {
/* No valid values left; drop back. */
i--;
if (i < 0)
break; /* overall iteration is finished */
if (op == C_ADD)
total += ctx->dscratch[i];
else
total *= ctx->dscratch[i];
} else {
/* Got a valid value; store it and move on. */
ctx->dscratch[i++] = j;
if (op == C_ADD)
total -= j;
else
total /= j;
ctx->dscratch[i] = 0;
}
} else {
if (total == (op == C_ADD ? 0 : 1))
solver_clue_candidate(ctx, diff, box);
i--;
if (op == C_ADD)
total += ctx->dscratch[i];
else
total *= ctx->dscratch[i];
}
}
break;
}
/*
* Do deductions based on the information we've now
* accumulated in ctx->iscratch. See the comments above in
* solver_clue_candidate explaining what data is left in here,
* and how it differs between DIFF_HARD and lower difficulty
* levels (hence the big if statement here).
*/
if (diff < DIFF_HARD) {
#ifdef STANDALONE_SOLVER
char prefix[256];
if (solver_show_working)
sprintf(prefix, "%*susing clue at (%d,%d):\n",
solver_recurse_depth*4, "",
sq[0]/w+1, sq[0]%w+1);
else
prefix[0] = '\0'; /* placate optimiser */
#endif
for (i = 0; i < n; i++)
for (j = 1; j <= w; j++) {
if (solver->cube[sq[i]*w+j-1] &&
!(ctx->iscratch[i] & (1 << j))) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
printf("%s%*s ruling out %d at (%d,%d)\n",
prefix, solver_recurse_depth*4, "",
j, sq[i]/w+1, sq[i]%w+1);
prefix[0] = '\0';
}
#endif
solver->cube[sq[i]*w+j-1] = 0;
ret = 1;
}
}
} else {
#ifdef STANDALONE_SOLVER
char prefix[256];
if (solver_show_working)
sprintf(prefix, "%*susing clue at (%d,%d):\n",
solver_recurse_depth*4, "",
sq[0]/w+1, sq[0]%w+1);
else
prefix[0] = '\0'; /* placate optimiser */
#endif
for (i = 0; i < 2*w; i++) {
int start = (i < w ? i*w : i-w);
int step = (i < w ? 1 : w);
for (j = 1; j <= w; j++) if (ctx->iscratch[i] & (1 << j)) {
#ifdef STANDALONE_SOLVER
char prefix2[256];
if (solver_show_working)
sprintf(prefix2, "%*s this clue requires %d in"
" %s %d:\n", solver_recurse_depth*4, "",
j, i < w ? "column" : "row", i%w+1);
else
prefix2[0] = '\0'; /* placate optimiser */
#endif
for (k = 0; k < w; k++) {
int pos = start + k*step;
if (ctx->whichbox[pos] != box &&
solver->cube[pos*w+j-1]) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
printf("%s%s%*s ruling out %d at (%d,%d)\n",
prefix, prefix2,
solver_recurse_depth*4, "",
j, pos/w+1, pos%w+1);
prefix[0] = prefix2[0] = '\0';
}
#endif
solver->cube[pos*w+j-1] = 0;
ret = 1;
}
}
}
}
/*
* Once we find one block we can do something with in
* this way, revert to trying easier deductions, so as
* not to generate solver diagnostics that make the
* problem look harder than it is. (We have to do this
* for the Hard deductions but not the Easy/Normal ones,
* because only the Hard deductions are cross-box.)
*/
if (ret)
return ret;
}
}
return ret;
}
static int solver_easy(struct latin_solver *solver, void *vctx)
{
/*
* Omit the EASY deductions when solving at NORMAL level, since
* the NORMAL deductions are a superset of them anyway and it
* saves on time and confusing solver diagnostics.
*
* Note that this breaks the natural semantics of the return
* value of latin_solver. Without this hack, you could determine
* a puzzle's difficulty in one go by trying to solve it at
* maximum difficulty and seeing what difficulty value was
* returned; but with this hack, solving an Easy puzzle on
* Normal difficulty will typically return Normal. Hence the
* uses of the solver to determine difficulty are all arranged
* so as to double-check by re-solving at the next difficulty
* level down and making sure it failed.
*/
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
if (ctx->diff > DIFF_EASY)
return 0;
return solver_common(solver, vctx, DIFF_EASY);
}
static int solver_normal(struct latin_solver *solver, void *vctx)
{
return solver_common(solver, vctx, DIFF_NORMAL);
}
static int solver_hard(struct latin_solver *solver, void *vctx)
{
return solver_common(solver, vctx, DIFF_HARD);
}
#define SOLVER(upper,title,func,lower) func,
static usersolver_t const keen_solvers[] = { DIFFLIST(SOLVER) };
static int transpose(int index, int w)
{
return (index % w) * w + (index / w);
}
static bool keen_valid(struct latin_solver *solver, void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
int w = ctx->w;
int box, i;
/*
* Iterate over each clue box and check it's satisfied.
*/
for (box = 0; box < ctx->nboxes; box++) {
int *sq = ctx->boxlist + ctx->boxes[box];
int n = ctx->boxes[box+1] - ctx->boxes[box];
long value = ctx->clues[box] & ~CMASK;
long op = ctx->clues[box] & CMASK;
bool fail = false;
switch (op) {
case C_ADD: {
long sum = 0;
for (i = 0; i < n; i++)
sum += solver->grid[transpose(sq[i], w)];
fail = (sum != value);
break;
}
case C_MUL: {
long remaining = value;
for (i = 0; i < n; i++) {
if (remaining % solver->grid[transpose(sq[i], w)]) {
fail = true;
break;
}
remaining /= solver->grid[transpose(sq[i], w)];
}
if (remaining != 1)
fail = true;
break;
}
case C_SUB:
assert(n == 2);
if (value != labs(solver->grid[transpose(sq[0], w)] -
solver->grid[transpose(sq[1], w)]))
fail = true;
break;
case C_DIV: {
int num, den;
assert(n == 2);
num = max(solver->grid[transpose(sq[0], w)],
solver->grid[transpose(sq[1], w)]);
den = min(solver->grid[transpose(sq[0], w)],
solver->grid[transpose(sq[1], w)]);
if (den * value != num)
fail = true;
break;
}
}
if (fail) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
printf("%*sclue at (%d,%d) is violated\n",
solver_recurse_depth*4, "",
sq[0]/w+1, sq[0]%w+1);
printf("%*s (%s clue with target %ld containing [",
solver_recurse_depth*4, "",
(op == C_ADD ? "addition" : op == C_SUB ? "subtraction":
op == C_MUL ? "multiplication" : "division"), value);
for (i = 0; i < n; i++)
printf(" %d", (int)solver->grid[transpose(sq[i], w)]);
printf(" ]\n");
}
#endif
return false;
}
}
return true;
}
static int solver(int w, DSF *dsf, long *clues, digit *soln, int maxdiff)
{
int a = w*w;
struct solver_ctx ctx;
int ret;
int i, j, n, m;
ctx.w = w;
ctx.soln = soln;
ctx.diff = maxdiff;
/*
* Transform the dsf-formatted clue list into one over which we
* can iterate more easily.
*
* Also transpose the x- and y-coordinates at this point,
* because the 'cube' array in the general Latin square solver
* puts x first (oops).
*/
for (ctx.nboxes = i = 0; i < a; i++)
if (dsf_canonify(dsf, i) == i)
ctx.nboxes++;
ctx.boxlist = snewn(a, int);
ctx.boxes = snewn(ctx.nboxes+1, int);
ctx.clues = snewn(ctx.nboxes, long);
ctx.whichbox = snewn(a, int);
for (n = m = i = 0; i < a; i++)
if (dsf_minimal(dsf, i) == i) {
ctx.clues[n] = clues[i];
ctx.boxes[n] = m;
for (j = 0; j < a; j++)
if (dsf_minimal(dsf, j) == i) {
ctx.boxlist[m++] = (j % w) * w + (j / w); /* transpose */
ctx.whichbox[ctx.boxlist[m-1]] = n;
}
n++;
}
assert(n == ctx.nboxes);
assert(m == a);
ctx.boxes[n] = m;
ctx.dscratch = snewn(a+1, digit);
ctx.iscratch = snewn(max(a+1, 4*w), int);
ret = latin_solver(soln, w, maxdiff,
DIFF_EASY, DIFF_HARD, DIFF_EXTREME,
DIFF_EXTREME, DIFF_UNREASONABLE,
keen_solvers, keen_valid, &ctx, NULL, NULL);
sfree(ctx.dscratch);
sfree(ctx.iscratch);
sfree(ctx.whichbox);
sfree(ctx.boxlist);
sfree(ctx.boxes);
sfree(ctx.clues);
return ret;
}
/* ----------------------------------------------------------------------
* Grid generation.
*/
static char *encode_block_structure(char *p, int w, DSF *dsf)
{
int i, currrun = 0;
char *orig, *q, *r, c;
orig = p;
/*
* Encode the block structure. We do this by encoding the
* pattern of dividing lines: first we iterate over the w*(w-1)
* internal vertical grid lines in ordinary reading order, then
* over the w*(w-1) internal horizontal ones in transposed
* reading order.
*
* We encode the number of non-lines between the lines; _ means
* zero (two adjacent divisions), a means 1, ..., y means 25,
* and z means 25 non-lines _and no following line_ (so that za
* means 26, zb 27 etc).
*/
for (i = 0; i <= 2*w*(w-1); i++) {
int x, y, p0, p1;
bool edge;
if (i == 2*w*(w-1)) {
edge = true; /* terminating virtual edge */
} else {
if (i < w*(w-1)) {
y = i/(w-1);
x = i%(w-1);
p0 = y*w+x;
p1 = y*w+x+1;
} else {
x = i/(w-1) - w;
y = i%(w-1);
p0 = y*w+x;
p1 = (y+1)*w+x;
}
edge = !dsf_equivalent(dsf, p0, p1);
}
if (edge) {
while (currrun > 25)
*p++ = 'z', currrun -= 25;
if (currrun)
*p++ = 'a'-1 + currrun;
else
*p++ = '_';
currrun = 0;
} else
currrun++;
}
/*
* Now go through and compress the string by replacing runs of
* the same letter with a single copy of that letter followed by
* a repeat count, where that makes it shorter. (This puzzle
* seems to generate enough long strings of _ to make this a
* worthwhile step.)
*/
for (q = r = orig; r < p ;) {
*q++ = c = *r;
for (i = 0; r+i < p && r[i] == c; i++);
r += i;
if (i == 2) {
*q++ = c;
} else if (i > 2) {
q += sprintf(q, "%d", i);
}
}
return q;
}
static const char *parse_block_structure(const char **p, int w, DSF *dsf)
{
int pos = 0;
int repc = 0, repn = 0;
dsf_reinit(dsf);
while (**p && (repn > 0 || **p != ',')) {
int c;
bool adv;
if (repn > 0) {
repn--;
c = repc;
} else if (**p == '_' || (**p >= 'a' && **p <= 'z')) {
c = (**p == '_' ? 0 : **p - 'a' + 1);
(*p)++;
if (**p && isdigit((unsigned char)**p)) {
repc = c;
repn = atoi(*p)-1;
while (**p && isdigit((unsigned char)**p)) (*p)++;
}
} else
return "Invalid character in game description";
adv = (c != 25); /* 'z' is a special case */
while (c-- > 0) {
int p0, p1;
/*
* Non-edge; merge the two dsf classes on either
* side of it.
*/
if (pos >= 2*w*(w-1))
return "Too much data in block structure specification";
if (pos < w*(w-1)) {
int y = pos/(w-1);
int x = pos%(w-1);
p0 = y*w+x;
p1 = y*w+x+1;
} else {
int x = pos/(w-1) - w;
int y = pos%(w-1);
p0 = y*w+x;
p1 = (y+1)*w+x;
}
dsf_merge(dsf, p0, p1);
pos++;
}
if (adv) {
pos++;
if (pos > 2*w*(w-1)+1)
return "Too much data in block structure specification";
}
}
/*
* When desc is exhausted, we expect to have gone exactly
* one space _past_ the end of the grid, due to the dummy
* edge at the end.
*/
if (pos != 2*w*(w-1)+1)
return "Not enough data in block structure specification";
return NULL;
}
static char *new_game_desc(const game_params *params, random_state *rs,
char **aux, bool interactive)
{
int w = params->w, a = w*w;
digit *grid, *soln;
int *order, *revorder, *singletons;
DSF *dsf;
long *clues, *cluevals;
int i, j, k, n, x, y, ret;
int diff = params->diff;
char *desc, *p;
/*
* Difficulty exceptions: 3x3 puzzles at difficulty Hard or
* higher are currently not generable - the generator will spin
* forever looking for puzzles of the appropriate difficulty. We
* dial each of these down to the next lower difficulty.
*
* Remember to re-test this whenever a change is made to the
* solver logic!
*
* I tested it using the following shell command:
for d in e n h x u; do
for i in {3..9}; do
echo ./keen --generate 1 ${i}d${d}
perl -e 'alarm 30; exec @ARGV' ./keen --generate 5 ${i}d${d} >/dev/null \
|| echo broken
done
done
* Of course, it's better to do that after taking the exceptions
* _out_, so as to detect exceptions that should be removed as
* well as those which should be added.
*/
if (w == 3 && diff > DIFF_NORMAL)
diff = DIFF_NORMAL;
grid = NULL;
order = snewn(a, int);
revorder = snewn(a, int);
singletons = snewn(a, int);
dsf = dsf_new_min(a);
clues = snewn(a, long);
cluevals = snewn(a, long);
soln = snewn(a, digit);
while (1) {
/*
* First construct a latin square to be the solution.
*/
sfree(grid);
grid = latin_generate(w, rs);
/*
* Divide the grid into arbitrarily sized blocks, but so as
* to arrange plenty of dominoes which can be SUB/DIV clues.
* We do this by first placing dominoes at random for a
* while, then tying the remaining singletons one by one
* into neighbouring blocks.
*/
for (i = 0; i < a; i++)
order[i] = i;
shuffle(order, a, sizeof(*order), rs);
for (i = 0; i < a; i++)
revorder[order[i]] = i;
for (i = 0; i < a; i++)
singletons[i] = true;
dsf_reinit(dsf);
/* Place dominoes. */
for (i = 0; i < a; i++) {
if (singletons[i]) {
int best = -1;
x = i % w;
y = i / w;
if (x > 0 && singletons[i-1] &&
(best == -1 || revorder[i-1] < revorder[best]))
best = i-1;
if (x+1 < w && singletons[i+1] &&
(best == -1 || revorder[i+1] < revorder[best]))
best = i+1;
if (y > 0 && singletons[i-w] &&
(best == -1 || revorder[i-w] < revorder[best]))
best = i-w;
if (y+1 < w && singletons[i+w] &&
(best == -1 || revorder[i+w] < revorder[best]))
best = i+w;
/*
* When we find a potential domino, we place it with
* probability 3/4, which seems to strike a decent
* balance between plenty of dominoes and leaving
* enough singletons to make interesting larger
* shapes.
*/
if (best >= 0 && random_upto(rs, 4)) {
singletons[i] = singletons[best] = false;
dsf_merge(dsf, i, best);
}
}
}
/* Fold in singletons. */
for (i = 0; i < a; i++) {