-
Notifications
You must be signed in to change notification settings - Fork 6
/
range.c
1836 lines (1575 loc) · 55.7 KB
/
range.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
/*
* range.c: implementation of the Nikoli game 'Kurodoko' / 'Kuromasu'.
*/
/*
* Puzzle rules: the player is given a WxH grid of white squares, some
* of which contain numbers. The goal is to paint some of the squares
* black, such that:
*
* - no cell (err, cell = square) with a number is painted black
* - no black cells have an adjacent (horz/vert) black cell
* - the white cells are all connected (through other white cells)
* - if a cell contains a number n, let h and v be the lengths of the
* maximal horizontal and vertical white sequences containing that
* cell. Then n must equal h + v - 1.
*/
/* example instance with its encoding and textual representation, both
* solved and unsolved (made by thegame.solve and thegame.text_format)
*
* +--+--+--+--+--+--+--+
* | | | | | 7| | |
* +--+--+--+--+--+--+--+
* | 3| | | | | | 8|
* +--+--+--+--+--+--+--+
* | | | | | | 5| |
* +--+--+--+--+--+--+--+
* | | | 7| | 7| | |
* +--+--+--+--+--+--+--+
* | |13| | | | | |
* +--+--+--+--+--+--+--+
* | 4| | | | | | 8|
* +--+--+--+--+--+--+--+
* | | | 4| | | | |
* +--+--+--+--+--+--+--+
*
* 7x7:d7b3e8e5c7a7c13e4d8b4d
*
* +--+--+--+--+--+--+--+
* |..|..|..|..| 7|..|..|
* +--+--+--+--+--+--+--+
* | 3|..|##|..|##|..| 8|
* +--+--+--+--+--+--+--+
* |##|..|..|##|..| 5|..|
* +--+--+--+--+--+--+--+
* |..|..| 7|..| 7|##|..|
* +--+--+--+--+--+--+--+
* |..|13|..|..|..|..|..|
* +--+--+--+--+--+--+--+
* | 4|..|##|..|##|..| 8|
* +--+--+--+--+--+--+--+
* |##|..| 4|..|..|##|..|
* +--+--+--+--+--+--+--+
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include "puzzles.h"
#include <stdarg.h>
#define setmember(obj, field) ( (obj) . field = field )
static char *nfmtstr(int n, const char *fmt, ...) {
va_list va;
char *ret = snewn(n+1, char);
va_start(va, fmt);
vsprintf(ret, fmt, va);
va_end(va);
return ret;
}
#define SWAP(type, lvar1, lvar2) do { \
type tmp = (lvar1); \
(lvar1) = (lvar2); \
(lvar2) = tmp; \
} while (0)
/* ----------------------------------------------------------------------
* Game parameters, presets, states
*/
typedef signed char puzzle_size;
struct game_params {
puzzle_size w;
puzzle_size h;
};
struct game_state {
struct game_params params;
bool has_cheated, was_solved;
puzzle_size *grid;
};
#define DEFAULT_PRESET 0
static struct game_params range_presets[] = {{9, 6}, {12, 8}, {13, 9}, {16, 11}};
/* rationale: I want all four combinations of {odd/even, odd/even}, as
* they play out differently with respect to two-way symmetry. I also
* want them to be generated relatively fast yet still be large enough
* to be entertaining for a decent amount of time, and I want them to
* make good use of monitor real estate (the typical screen resolution
* is why I do 13x9 and not 9x13).
*/
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
*ret = range_presets[DEFAULT_PRESET]; /* structure copy */
return ret;
}
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)
{
game_params *ret;
if (i < 0 || i >= lenof(range_presets)) return false;
ret = default_params();
*ret = range_presets[i]; /* struct copy */
*params = ret;
*name = nfmtstr(40, "%d x %d", range_presets[i].w, range_presets[i].h);
return true;
}
static void free_params(game_params *params)
{
sfree(params);
}
static void decode_params(game_params *params, char const *string)
{
/* FIXME check for puzzle_size overflow and decoding issues */
params->w = params->h = atoi(string);
while (*string && isdigit((unsigned char) *string)) ++string;
if (*string == 'x') {
string++;
params->h = atoi(string);
while (*string && isdigit((unsigned char)*string)) string++;
}
}
static char *encode_params(const game_params *params, bool full)
{
char str[80];
sprintf(str, "%dx%d", params->w, params->h);
return dupstr(str);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
ret = snewn(3, config_item);
ret[0].name = "Width";
ret[0].type = C_STRING;
ret[0].u.string.sval = nfmtstr(10, "%d", params->w);
ret[1].name = "Height";
ret[1].type = C_STRING;
ret[1].u.string.sval = nfmtstr(10, "%d", params->h);
ret[2].name = NULL;
ret[2].type = C_END;
return ret;
}
static game_params *custom_params(const config_item *configuration)
{
game_params *ret = snew(game_params);
ret->w = atoi(configuration[0].u.string.sval);
ret->h = atoi(configuration[1].u.string.sval);
return ret;
}
#define memdup(dst, src, n, type) do { \
dst = snewn(n, type); \
memcpy(dst, src, n * sizeof (type)); \
} while (0)
static game_state *dup_game(const game_state *state)
{
game_state *ret = snew(game_state);
int const n = state->params.w * state->params.h;
*ret = *state; /* structure copy */
/* copy the poin_tee_, set a new value of the poin_ter_ */
memdup(ret->grid, state->grid, n, puzzle_size);
return ret;
}
static void free_game(game_state *state)
{
sfree(state->grid);
sfree(state);
}
/* ----------------------------------------------------------------------
* The solver subsystem.
*
* The solver is used for two purposes:
* - To solve puzzles when the user selects `Solve'.
* - To test solubility of a grid as clues are being removed from it
* during the puzzle generation.
*
* It supports the following ways of reasoning:
*
* - A cell adjacent to a black cell must be white.
*
* - If painting a square black would bisect the white regions, that
* square is white (by finding biconnected components' cut points)
*
* - A cell with number n, covering at most k white squares in three
* directions must white-cover n-k squares in the last direction.
*
* - A cell with number n known to cover k squares, if extending the
* cover by one square in a given direction causes the cell to
* cover _more_ than n squares, that extension cell must be black.
*
* (either if the square already covers n, or if it extends into a
* chunk of size > n - k)
*
* - Recursion. Pick any cell and see if this leads to either a
* contradiction or a solution (and then act appropriately).
*
*
* TODO:
*
* (propagation upper limit)
* - If one has two numbers on the same line, the smaller limits the
* larger. Example: in |b|_|_|8|4|_|_|b|, only two _'s can be both
* white and connected to the "8" cell; so that cell will propagate
* at least four cells orthogonally to the displayed line (which is
* better than the current "at least 2").
*
* (propagation upper limit)
* - cells can't propagate into other cells if doing so exceeds that
* number. Example: in |b|4|.|.|2|b|, at most one _ can be white;
* otherwise, the |2| would have too many reaching white cells.
*
* (propagation lower and upper limit)
* - `Full Combo': in each four directions d_1 ... d_4, find a set of
* possible propagation distances S_1 ... S_4. For each i=1..4,
* for each x in S_i: if not exists (y, z, w) in the other sets
* such that (x+y+z+w+1 == clue value): then remove x from S_i.
* Repeat until this stabilizes. If any cell would contradict
*/
#define idx(i, j, w) ((i)*(w) + (j))
#define out_of_bounds(r, c, w, h) \
((r) < 0 || (r) >= h || (c) < 0 || (c) >= w)
typedef struct square {
puzzle_size r, c;
} square;
enum {BLACK = -2, WHITE, EMPTY};
/* white is for pencil marks, empty is undecided */
static int const dr[4] = {+1, 0, -1, 0};
static int const dc[4] = { 0, +1, 0, -1};
static int const cursors[4] = /* must match dr and dc */
{CURSOR_DOWN, CURSOR_RIGHT, CURSOR_UP, CURSOR_LEFT};
typedef struct move {
square square;
unsigned int colour: 1;
} move;
enum {M_BLACK = 0, M_WHITE = 1};
typedef move *(reasoning)(game_state *state,
int nclues,
const square *clues,
move *buf);
static reasoning solver_reasoning_not_too_big;
static reasoning solver_reasoning_adjacency;
static reasoning solver_reasoning_connectedness;
static reasoning solver_reasoning_recursion;
enum {
DIFF_NOT_TOO_BIG,
DIFF_ADJACENCY,
DIFF_CONNECTEDNESS,
DIFF_RECURSION
};
static move *solve_internal(const game_state *state, move *base, int diff);
static char *solve_game(const game_state *orig, const game_state *curpos,
const char *aux, const char **error)
{
int const n = orig->params.w * orig->params.h;
move *const base = snewn(n, move);
move *moves = solve_internal(orig, base, DIFF_RECURSION);
char *ret = NULL;
if (moves != NULL) {
int const k = moves - base;
char *str = ret = snewn(15*k + 2, char);
char colour[2] = "BW";
move *it;
*str++ = 'S';
*str = '\0';
for (it = base; it < moves; ++it)
str += sprintf(str, "%c,%d,%d", colour[it->colour],
it->square.r, it->square.c);
} else *error = "This puzzle instance contains a contradiction";
sfree(base);
return ret;
}
static square *find_clues(const game_state *state, int *ret_nclues);
static move *do_solve(game_state *state,
int nclues,
const square *clues,
move *move_buffer,
int difficulty);
/* new_game_desc entry point in the solver subsystem */
static move *solve_internal(const game_state *state, move *base, int diff)
{
int nclues;
square *const clues = find_clues(state, &nclues);
game_state *dup = dup_game(state);
move *const moves = do_solve(dup, nclues, clues, base, diff);
free_game(dup);
sfree(clues);
return moves;
}
static reasoning *const reasonings[] = {
solver_reasoning_not_too_big,
solver_reasoning_adjacency,
solver_reasoning_connectedness,
solver_reasoning_recursion
};
static move *do_solve(game_state *state,
int nclues,
const square *clues,
move *move_buffer,
int difficulty)
{
struct move *buf = move_buffer, *oldbuf;
int i;
do {
oldbuf = buf;
for (i = 0; i < lenof(reasonings) && i <= difficulty; ++i) {
/* only recurse if all else fails */
if (i == DIFF_RECURSION && buf > oldbuf) continue;
buf = (*reasonings[i])(state, nclues, clues, buf);
if (buf == NULL) return NULL;
}
} while (buf > oldbuf);
return buf;
}
#define MASK(n) (1 << ((n) + 2))
static int runlength(puzzle_size r, puzzle_size c,
puzzle_size dr, puzzle_size dc,
const game_state *state, int colourmask)
{
int const w = state->params.w, h = state->params.h;
int sz = 0;
while (true) {
int cell = idx(r, c, w);
if (out_of_bounds(r, c, w, h)) break;
if (state->grid[cell] > 0) {
if (!(colourmask & ~(MASK(BLACK) | MASK(WHITE) | MASK(EMPTY))))
break;
} else if (!(MASK(state->grid[cell]) & colourmask)) break;
++sz;
r += dr;
c += dc;
}
return sz;
}
static void solver_makemove(puzzle_size r, puzzle_size c, int colour,
game_state *state, move **buffer_ptr)
{
int const cell = idx(r, c, state->params.w);
if (out_of_bounds(r, c, state->params.w, state->params.h)) return;
if (state->grid[cell] != EMPTY) return;
setmember((*buffer_ptr)->square, r);
setmember((*buffer_ptr)->square, c);
setmember(**buffer_ptr, colour);
++*buffer_ptr;
state->grid[cell] = (colour == M_BLACK ? BLACK : WHITE);
}
static move *solver_reasoning_adjacency(game_state *state,
int nclues,
const square *clues,
move *buf)
{
int r, c, i;
for (r = 0; r < state->params.h; ++r)
for (c = 0; c < state->params.w; ++c) {
int const cell = idx(r, c, state->params.w);
if (state->grid[cell] != BLACK) continue;
for (i = 0; i < 4; ++i)
solver_makemove(r + dr[i], c + dc[i], M_WHITE, state, &buf);
}
return buf;
}
enum {NOT_VISITED = -1};
static int dfs_biconnect_visit(puzzle_size r, puzzle_size c,
game_state *state,
square *dfs_parent, int *dfs_depth,
move **buf);
static move *solver_reasoning_connectedness(game_state *state,
int nclues,
const square *clues,
move *buf)
{
int const w = state->params.w, h = state->params.h, n = w * h;
square *const dfs_parent = snewn(n, square);
int *const dfs_depth = snewn(n, int);
int i;
for (i = 0; i < n; ++i) {
dfs_parent[i].r = NOT_VISITED;
dfs_depth[i] = -n;
}
for (i = 0; i < n && state->grid[i] == BLACK; ++i);
dfs_parent[i].r = i / w;
dfs_parent[i].c = i % w; /* `dfs root`.parent == `dfs root` */
dfs_depth[i] = 0;
dfs_biconnect_visit(i / w, i % w, state, dfs_parent, dfs_depth, &buf);
sfree(dfs_parent);
sfree(dfs_depth);
return buf;
}
/* returns the `lowpoint` of (r, c) */
static int dfs_biconnect_visit(puzzle_size r, puzzle_size c,
game_state *state,
square *dfs_parent, int *dfs_depth,
move **buf)
{
const puzzle_size w = state->params.w, h = state->params.h;
int const i = idx(r, c, w), mydepth = dfs_depth[i];
int lowpoint = mydepth, j, nchildren = 0;
for (j = 0; j < 4; ++j) {
const puzzle_size rr = r + dr[j], cc = c + dc[j];
int const cell = idx(rr, cc, w);
if (out_of_bounds(rr, cc, w, h)) continue;
if (state->grid[cell] == BLACK) continue;
if (dfs_parent[cell].r == NOT_VISITED) {
int child_lowpoint;
dfs_parent[cell].r = r;
dfs_parent[cell].c = c;
dfs_depth[cell] = mydepth + 1;
child_lowpoint = dfs_biconnect_visit(rr, cc, state, dfs_parent,
dfs_depth, buf);
if (child_lowpoint >= mydepth && mydepth > 0)
solver_makemove(r, c, M_WHITE, state, buf);
lowpoint = min(lowpoint, child_lowpoint);
++nchildren;
} else if (rr != dfs_parent[i].r || cc != dfs_parent[i].c) {
lowpoint = min(lowpoint, dfs_depth[cell]);
}
}
if (mydepth == 0 && nchildren >= 2)
solver_makemove(r, c, M_WHITE, state, buf);
return lowpoint;
}
static move *solver_reasoning_not_too_big(game_state *state,
int nclues,
const square *clues,
move *buf)
{
int const w = state->params.w, runmasks[4] = {
~(MASK(BLACK) | MASK(EMPTY)),
MASK(EMPTY),
~(MASK(BLACK) | MASK(EMPTY)),
~(MASK(BLACK))
};
enum {RUN_WHITE, RUN_EMPTY, RUN_BEYOND, RUN_SPACE};
int i, runlengths[4][4];
for (i = 0; i < nclues; ++i) {
int j, k, whites, space;
const puzzle_size row = clues[i].r, col = clues[i].c;
int const clue = state->grid[idx(row, col, w)];
for (j = 0; j < 4; ++j) {
puzzle_size r = row + dr[j], c = col + dc[j];
runlengths[RUN_SPACE][j] = 0;
for (k = 0; k <= RUN_SPACE; ++k) {
int l = runlength(r, c, dr[j], dc[j], state, runmasks[k]);
if (k < RUN_SPACE) {
runlengths[k][j] = l;
r += dr[j] * l;
c += dc[j] * l;
}
runlengths[RUN_SPACE][j] += l;
}
}
whites = 1;
for (j = 0; j < 4; ++j) whites += runlengths[RUN_WHITE][j];
for (j = 0; j < 4; ++j) {
int const delta = 1 + runlengths[RUN_WHITE][j];
const puzzle_size r = row + delta * dr[j];
const puzzle_size c = col + delta * dc[j];
if (whites == clue) {
solver_makemove(r, c, M_BLACK, state, &buf);
continue;
}
if (runlengths[RUN_EMPTY][j] == 1 &&
whites
+ runlengths[RUN_EMPTY][j]
+ runlengths[RUN_BEYOND][j]
> clue) {
solver_makemove(r, c, M_BLACK, state, &buf);
continue;
}
if (whites
+ runlengths[RUN_EMPTY][j]
+ runlengths[RUN_BEYOND][j]
> clue) {
runlengths[RUN_SPACE][j] =
runlengths[RUN_WHITE][j] +
runlengths[RUN_EMPTY][j] - 1;
if (runlengths[RUN_EMPTY][j] == 1)
solver_makemove(r, c, M_BLACK, state, &buf);
}
}
space = 1;
for (j = 0; j < 4; ++j) space += runlengths[RUN_SPACE][j];
for (j = 0; j < 4; ++j) {
puzzle_size r = row + dr[j], c = col + dc[j];
int k = space - runlengths[RUN_SPACE][j];
if (k >= clue) continue;
for (; k < clue; ++k, r += dr[j], c += dc[j])
solver_makemove(r, c, M_WHITE, state, &buf);
}
}
return buf;
}
static move *solver_reasoning_recursion(game_state *state,
int nclues,
const square *clues,
move *buf)
{
int const w = state->params.w, n = w * state->params.h;
int cell, colour;
for (cell = 0; cell < n; ++cell) {
int const r = cell / w, c = cell % w;
int i;
game_state *newstate;
move *recursive_result;
if (state->grid[cell] != EMPTY) continue;
/* FIXME: add enum alias for smallest and largest (or N) */
for (colour = M_BLACK; colour <= M_WHITE; ++colour) {
newstate = dup_game(state);
newstate->grid[cell] = colour == M_BLACK ? BLACK : WHITE;
recursive_result = do_solve(newstate, nclues, clues, buf,
DIFF_RECURSION);
if (recursive_result == NULL) {
free_game(newstate);
solver_makemove(r, c, M_BLACK + M_WHITE - colour, state, &buf);
return buf;
}
for (i = 0; i < n && newstate->grid[i] != EMPTY; ++i);
free_game(newstate);
if (i == n) return buf;
}
}
return buf;
}
static square *find_clues(const game_state *state, int *ret_nclues)
{
int r, c, i, nclues = 0;
square *ret = snewn(state->params.w * state->params.h, struct square);
for (i = r = 0; r < state->params.h; ++r)
for (c = 0; c < state->params.w; ++c, ++i)
if (state->grid[i] > 0) {
ret[nclues].r = r;
ret[nclues].c = c;
++nclues;
}
*ret_nclues = nclues;
return sresize(ret, nclues + (nclues == 0), square);
}
/* ----------------------------------------------------------------------
* Puzzle generation
*
* Generating kurodoko instances is rather straightforward:
*
* - Start with a white grid and add black squares at randomly chosen
* locations, unless colouring that square black would violate
* either the adjacency or connectedness constraints.
*
* - For each white square, compute the number it would contain if it
* were given as a clue.
*
* - From a starting point of "give _every_ white square as a clue",
* for each white square (in a random order), see if the board is
* solvable when that square is not given as a clue. If not, don't
* give it as a clue, otherwise do.
*
* This never fails, but it's only _almost_ what I do. The real final
* step is this:
*
* - From a starting point of "give _every_ white square as a clue",
* first remove all clues that are two-way rotationally symmetric
* to a black square. If this leaves the puzzle unsolvable, throw
* it out and try again. Otherwise, remove all _pairs_ of clues
* (that are rotationally symmetric) which can be removed without
* rendering the puzzle unsolvable.
*
* This can fail even if one only removes the black and symmetric
* clues; indeed it happens often (avg. once or twice per puzzle) when
* generating 1xN instances. (If you add black cells they must be in
* the end, and if you only add one, it's ambiguous where).
*/
/* forward declarations of internal calls */
static void newdesc_choose_black_squares(game_state *state,
const int *shuffle_1toN);
static void newdesc_compute_clues(game_state *state);
static int newdesc_strip_clues(game_state *state, int *shuffle_1toN);
static char *newdesc_encode_game_description(int n, puzzle_size *grid);
static char *new_game_desc(const game_params *params, random_state *rs,
char **aux, bool interactive)
{
int const w = params->w, h = params->h, n = w * h;
puzzle_size *const grid = snewn(n, puzzle_size);
int *const shuffle_1toN = snewn(n, int);
int i, clues_removed;
char *encoding;
game_state state;
state.params = *params;
state.grid = grid;
interactive = false; /* I don't need it, I shouldn't use it*/
for (i = 0; i < n; ++i) shuffle_1toN[i] = i;
while (true) {
shuffle(shuffle_1toN, n, sizeof (int), rs);
newdesc_choose_black_squares(&state, shuffle_1toN);
newdesc_compute_clues(&state);
shuffle(shuffle_1toN, n, sizeof (int), rs);
clues_removed = newdesc_strip_clues(&state, shuffle_1toN);
if (clues_removed < 0) continue; else break;
}
encoding = newdesc_encode_game_description(n, grid);
sfree(grid);
sfree(shuffle_1toN);
return encoding;
}
static int dfs_count_white(game_state *state, int cell);
static void newdesc_choose_black_squares(game_state *state,
const int *shuffle_1toN)
{
int const w = state->params.w, h = state->params.h, n = w * h;
int k, any_white_cell, n_black_cells;
for (k = 0; k < n; ++k) state->grid[k] = WHITE;
any_white_cell = shuffle_1toN[n - 1];
n_black_cells = 0;
/* I like the puzzles that result from n / 3, but maybe this
* could be made a (generation, i.e. non-full) parameter? */
for (k = 0; k < n / 3; ++k) {
int const i = shuffle_1toN[k], c = i % w, r = i / w;
int j;
for (j = 0; j < 4; ++j) {
int const rr = r + dr[j], cc = c + dc[j], cell = idx(rr, cc, w);
/* if you're out of bounds, we skip you */
if (out_of_bounds(rr, cc, w, h)) continue;
if (state->grid[cell] == BLACK) break; /* I can't be black */
} if (j < 4) continue; /* I have black neighbour: I'm white */
state->grid[i] = BLACK;
++n_black_cells;
j = dfs_count_white(state, any_white_cell);
if (j + n_black_cells < n) {
state->grid[i] = WHITE;
--n_black_cells;
}
}
}
static void newdesc_compute_clues(game_state *state)
{
int const w = state->params.w, h = state->params.h;
int r, c;
for (r = 0; r < h; ++r) {
int run_size = 0, c, cc;
for (c = 0; c <= w; ++c) {
if (c == w || state->grid[idx(r, c, w)] == BLACK) {
for (cc = c - run_size; cc < c; ++cc)
state->grid[idx(r, cc, w)] += run_size;
run_size = 0;
} else ++run_size;
}
}
for (c = 0; c < w; ++c) {
int run_size = 0, r, rr;
for (r = 0; r <= h; ++r) {
if (r == h || state->grid[idx(r, c, w)] == BLACK) {
for (rr = r - run_size; rr < r; ++rr)
state->grid[idx(rr, c, w)] += run_size;
run_size = 0;
} else ++run_size;
}
}
}
#define rotate(x) (n - 1 - (x))
static int newdesc_strip_clues(game_state *state, int *shuffle_1toN)
{
int const w = state->params.w, n = w * state->params.h;
move *const move_buffer = snewn(n, move);
move *buf;
game_state *dupstate;
/*
* do a partition/pivot of shuffle_1toN into three groups:
* (1) squares rotationally-symmetric to (3)
* (2) squares not in (1) or (3)
* (3) black squares
*
* They go from [0, left), [left, right) and [right, n) in
* shuffle_1toN (and from there into state->grid[ ])
*
* Then, remove clues from the grid one by one in shuffle_1toN
* order, until the solver becomes unhappy. If we didn't remove
* all of (1), return (-1). Else, we're happy.
*/
/* do the partition */
int clues_removed, k = 0, left = 0, right = n;
for (;; ++k) {
while (k < right && state->grid[shuffle_1toN[k]] == BLACK) {
--right;
SWAP(int, shuffle_1toN[right], shuffle_1toN[k]);
assert(state->grid[shuffle_1toN[right]] == BLACK);
}
if (k >= right) break;
assert (k >= left);
if (state->grid[rotate(shuffle_1toN[k])] == BLACK) {
SWAP(int, shuffle_1toN[k], shuffle_1toN[left]);
++left;
}
assert (state->grid[rotate(shuffle_1toN[k])] != BLACK
|| k == left - 1);
}
for (k = 0; k < left; ++k) {
assert (state->grid[rotate(shuffle_1toN[k])] == BLACK);
state->grid[shuffle_1toN[k]] = EMPTY;
}
for (k = left; k < right; ++k) {
assert (state->grid[rotate(shuffle_1toN[k])] != BLACK);
assert (state->grid[shuffle_1toN[k]] != BLACK);
}
for (k = right; k < n; ++k) {
assert (state->grid[shuffle_1toN[k]] == BLACK);
state->grid[shuffle_1toN[k]] = EMPTY;
}
clues_removed = (left - 0) + (n - right);
dupstate = dup_game(state);
buf = solve_internal(dupstate, move_buffer, DIFF_RECURSION - 1);
free_game(dupstate);
if (buf - move_buffer < clues_removed) {
/* branch prediction: I don't think I'll go here */
clues_removed = -1;
goto ret;
}
for (k = left; k < right; ++k) {
const int i = shuffle_1toN[k], j = rotate(i);
int const clue = state->grid[i], clue_rot = state->grid[j];
if (clue == BLACK) continue;
state->grid[i] = state->grid[j] = EMPTY;
dupstate = dup_game(state);
buf = solve_internal(dupstate, move_buffer, DIFF_RECURSION - 1);
free_game(dupstate);
clues_removed += 2 - (i == j);
/* if i is the center square, then i == (j = rotate(i))
* when i and j are one, removing i and j removes only one */
if (buf - move_buffer == clues_removed) continue;
/* if the solver is sound, refilling all removed clues means
* we have filled all squares, i.e. solved the puzzle. */
state->grid[i] = clue;
state->grid[j] = clue_rot;
clues_removed -= 2 - (i == j);
}
ret:
sfree(move_buffer);
return clues_removed;
}
static int dfs_count_rec(puzzle_size *grid, int r, int c, int w, int h)
{
int const cell = idx(r, c, w);
if (out_of_bounds(r, c, w, h)) return 0;
if (grid[cell] != WHITE) return 0;
grid[cell] = EMPTY;
return 1 +
dfs_count_rec(grid, r + 0, c + 1, w, h) +
dfs_count_rec(grid, r + 0, c - 1, w, h) +
dfs_count_rec(grid, r + 1, c + 0, w, h) +
dfs_count_rec(grid, r - 1, c + 0, w, h);
}
static int dfs_count_white(game_state *state, int cell)
{
int const w = state->params.w, h = state->params.h, n = w * h;
int const r = cell / w, c = cell % w;
int i, k = dfs_count_rec(state->grid, r, c, w, h);
for (i = 0; i < n; ++i)
if (state->grid[i] == EMPTY)
state->grid[i] = WHITE;
return k;
}
static const char *validate_params(const game_params *params, bool full)
{
int const w = params->w, h = params->h;
if (w < 1) return "Error: width is less than 1";
if (h < 1) return "Error: height is less than 1";
if (w * h < 1) return "Error: size is less than 1";
if (w + h - 1 > SCHAR_MAX) return "Error: w + h is too big";
/* I might be unable to store clues in my puzzle_size *grid; */
if (full) {
if (w == 2 && h == 2) return "Error: can't create 2x2 puzzles";
if (w == 1 && h == 2) return "Error: can't create 1x2 puzzles";
if (w == 2 && h == 1) return "Error: can't create 2x1 puzzles";
if (w == 1 && h == 1) return "Error: can't create 1x1 puzzles";
}
return NULL;
}
/* Definition: a puzzle instance is _good_ if:
* - it has a unique solution
* - the solver can find this solution without using recursion
* - the solution contains at least one black square
* - the clues are 2-way rotationally symmetric
*
* (the idea being: the generator can not output any _bad_ puzzles)
*
* Theorem: validate_params, when full != 0, discards exactly the set
* of parameters for which there are _no_ good puzzle instances.
*
* Proof: it's an immediate consequence of the five lemmas below.
*
* Observation: not only do puzzles on non-tiny grids exist, the
* generator is pretty fast about coming up with them. On my pre-2004
* desktop box, it generates 100 puzzles on the highest preset (16x11)
* in 8.383 seconds, or <= 0.1 second per puzzle.
*
* ----------------------------------------------------------------------
*
* Lemma: On a 1x1 grid, there are no good puzzles.
*
* Proof: the one square can't be a clue because at least one square
* is black. But both a white square and a black square satisfy the
* solution criteria, so the puzzle is ambiguous (and hence bad).
*
* Lemma: On a 1x2 grid, there are no good puzzles.
*
* Proof: let's name the squares l and r. Note that there can be at
* most one black square, or adjacency is violated. By assumption at
* least one square is black, so let's call that one l. By clue
* symmetry, neither l nor r can be given as a clue, so the puzzle
* instance is blank and thus ambiguous.
*
* Corollary: On a 2x1 grid, there are no good puzzles.
* Proof: rotate the above proof 90 degrees ;-)
*
* ----------------------------------------------------------------------
*
* Lemma: On a 2x2 grid, there are no soluble puzzles with 2-way
* rotational symmetric clues and at least one black square.
*
* Proof: Let's name the squares a, b, c, and d, with a and b on the
* top row, a and c in the left column. Let's consider the case where
* a is black. Then no other square can be black: b and c would both
* violate the adjacency constraint; d would disconnect b from c.
*
* So exactly one square is black (and by 4-way rotation symmetry of
* the 2x2 square, it doesn't matter which one, so let's stick to a).
* By 2-way rotational symmetry of the clues and the rule about not
* painting numbers black, neither a nor d can be clues. A blank
* puzzle would be ambiguous, so one of {b, c} is a clue; by symmetry,
* so is the other one.
*
* It is readily seen that their clue value is 2. But "a is black"
* and "d is black" are both valid solutions in this case, so the
* puzzle is ambiguous (and hence bad).
*
* ----------------------------------------------------------------------
*
* Lemma: On a wxh grid with w, h >= 1 and (w > 2 or h > 2), there is
* at least one good puzzle.
*
* Proof: assume that w > h (otherwise rotate the proof again). Paint
* the top left and bottom right corners black, and fill a clue into
* all the other squares. Present this board to the solver code (or
* player, hypothetically), except with the two black squares as blank
* squares.
*
* For an Nx1 puzzle, observe that every clue is N - 2, and there are
* N - 2 of them in one connected sequence, so the remaining two
* squares can be deduced to be black, which solves the puzzle.
*
* For any other puzzle, let j be a cell in the same row as a black
* cell, but not in the same column (such a cell doesn't exist in 2x3