-
Notifications
You must be signed in to change notification settings - Fork 1
/
keen.c
2416 lines (2115 loc) · 60.5 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.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
#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;
};
struct clues {
int refcount;
int w;
int *dsf;
long *clues;
};
struct game_state {
game_params par;
struct clues *clues;
digit *grid;
int *pencil; /* bitmaps using bits 1<<1..1<<n */
int completed, cheated;
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->w = 6;
ret->diff = DIFF_NORMAL;
return ret;
}
const static struct game_params keen_presets[] = {
{ 4, DIFF_EASY },
{ 5, DIFF_EASY },
{ 6, DIFF_EASY },
{ 6, DIFF_NORMAL },
{ 6, DIFF_HARD },
{ 6, DIFF_EXTREME },
{ 6, DIFF_UNREASONABLE },
{ 9, DIFF_NORMAL },
};
static int 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", ret->w, ret->w, keen_diffnames[ret->diff]);
*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++;
}
}
}
static char *encode_params(const game_params *params, int full)
{
char ret[80];
sprintf(ret, "%d", params->w);
if (full)
sprintf(ret + strlen(ret), "d%c", keen_diffchars[params->diff]);
return dupstr(ret);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(3, config_item);
ret[0].name = "Grid size";
ret[0].type = C_STRING;
sprintf(buf, "%d", params->w);
ret[0].sval = dupstr(buf);
ret[0].ival = 0;
ret[1].name = "Difficulty";
ret[1].type = C_CHOICES;
ret[1].sval = DIFFCONFIG;
ret[1].ival = params->diff;
ret[2].name = NULL;
ret[2].type = C_END;
ret[2].sval = NULL;
ret[2].ival = 0;
return ret;
}
static game_params *custom_params(const config_item *cfg)
{
game_params *ret = snew(game_params);
ret->w = atoi(cfg[0].sval);
ret->diff = cfg[1].ival;
return ret;
}
static char *validate_params(const game_params *params, int 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.
*/
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;
if (diff == DIFF_HARD) {
for (i = 0; i < n; 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;
}
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 solver(int w, int *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_canonify(dsf, i) == i) {
ctx.clues[n] = clues[i];
ctx.boxes[n] = m;
for (j = 0; j < a; j++)
if (dsf_canonify(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, &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, int *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, 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_canonify(dsf, p0) != dsf_canonify(dsf, 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 char *parse_block_structure(const char **p, int w, int *dsf)
{
int a = w*w;
int pos = 0;
int repc = 0, repn = 0;
dsf_init(dsf, a);
while (**p && (repn > 0 || **p != ',')) {
int c, 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, int interactive)
{
int w = params->w, a = w*w;
digit *grid, *soln;
int *order, *revorder, *singletons, *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 = snew_dsf(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_init(dsf, a);
/* 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++) {
if (singletons[i]) {
int best = -1;
x = i % w;
y = i / w;
if (x > 0 && dsf_size(dsf, i-1) < MAXBLK &&
(best == -1 || revorder[i-1] < revorder[best]))
best = i-1;
if (x+1 < w && dsf_size(dsf, i+1) < MAXBLK &&
(best == -1 || revorder[i+1] < revorder[best]))
best = i+1;
if (y > 0 && dsf_size(dsf, i-w) < MAXBLK &&
(best == -1 || revorder[i-w] < revorder[best]))
best = i-w;
if (y+1 < w && dsf_size(dsf, i+w) < MAXBLK &&
(best == -1 || revorder[i+w] < revorder[best]))
best = i+w;
if (best >= 0) {
singletons[i] = singletons[best] = FALSE;
dsf_merge(dsf, i, best);
}
}
}
/* Quit and start again if we have any singletons left over
* which we weren't able to do anything at all with. */
for (i = 0; i < a; i++)
if (singletons[i])
break;
if (i < a)
continue;
/*
* Decide what would be acceptable clues for each block.
*
* Blocks larger than 2 have free choice of ADD or MUL;
* blocks of size 2 can be anything in principle (except
* that they can only be DIV if the two numbers have an
* integer quotient, of course), but we rule out (or try to
* avoid) some clues because they're of low quality.
*
* Hence, we iterate once over the grid, stopping at the
* canonical element of every >2 block and the _non_-
* canonical element of every 2-block; the latter means that
* we can make our decision about a 2-block in the knowledge
* of both numbers in it.
*
* We reuse the 'singletons' array (finished with in the
* above loop) to hold information about which blocks are
* suitable for what.
*/
#define F_ADD 0x01
#define F_SUB 0x02
#define F_MUL 0x04
#define F_DIV 0x08
#define BAD_SHIFT 4
for (i = 0; i < a; i++) {
singletons[i] = 0;
j = dsf_canonify(dsf, i);
k = dsf_size(dsf, j);
if (j == i && k > 2) {
singletons[j] |= F_ADD | F_MUL;
} else if (j != i && k == 2) {
/* Fetch the two numbers and sort them into order. */
int p = grid[j], q = grid[i], v;
if (p < q) {
int t = p; p = q; q = t;
}
/*
* Addition clues are always allowed, but we try to
* avoid sums of 3, 4, (2w-1) and (2w-2) if we can,
* because they're too easy - they only leave one
* option for the pair of numbers involved.
*/
v = p + q;
if (v > 4 && v < 2*w-2)
singletons[j] |= F_ADD;
else
singletons[j] |= F_ADD << BAD_SHIFT;
/*
* Multiplication clues: above Normal difficulty, we
* prefer (but don't absolutely insist on) clues of
* this type which leave multiple options open.
*/
v = p * q;
n = 0;
for (k = 1; k <= w; k++)
if (v % k == 0 && v / k <= w && v / k != k)
n++;
if (n <= 2 && diff > DIFF_NORMAL)
singletons[j] |= F_MUL << BAD_SHIFT;
else
singletons[j] |= F_MUL;
/*
* Subtraction: we completely avoid a difference of
* w-1.
*/
v = p - q;
if (v < w-1)
singletons[j] |= F_SUB;
/*
* Division: for a start, the quotient must be an
* integer or the clue type is impossible. Also, we
* never use quotients strictly greater than w/2,
* because they're not only too easy but also
* inelegant.
*/
if (p % q == 0 && 2 * (p / q) <= w)
singletons[j] |= F_DIV;
}
}
/*
* Actually choose a clue for each block, trying to keep the
* numbers of each type even, and starting with the
* preferred candidates for each type where possible.
*
* I'm sure there should be a faster algorithm for doing
* this, but I can't be bothered: O(N^2) is good enough when
* N is at most the number of dominoes that fits into a 9x9
* square.
*/
shuffle(order, a, sizeof(*order), rs);
for (i = 0; i < a; i++)
clues[i] = 0;
while (1) {
int done_something = FALSE;
for (k = 0; k < 4; k++) {
long clue;
int good, bad;
switch (k) {
case 0: clue = C_DIV; good = F_DIV; break;
case 1: clue = C_SUB; good = F_SUB; break;
case 2: clue = C_MUL; good = F_MUL; break;
default /* case 3 */ : clue = C_ADD; good = F_ADD; break;
}
for (i = 0; i < a; i++) {
j = order[i];
if (singletons[j] & good) {
clues[j] = clue;