Fix an inaccurate comment.
[sgt/puzzles] / unfinished / divvy.c
CommitLineData
11d273f7 1/*
2 * Library code to divide up a rectangle into a number of equally
3 * sized ominoes, in a random fashion.
4 *
5 * Could use this for generating solved grids of
6 * http://www.nikoli.co.jp/ja/puzzles/block_puzzle/
7 * or for generating the playfield for Jigsaw Sudoku.
8 */
9
9d36cbd7 10/*
82ed4789 11 * This code is restricted to simply connected solutions: that is,
12 * no single polyomino may completely surround another (not even
13 * with a corner visible to the outside world, in the sense that a
14 * 7-omino can `surround' a single square).
15 *
16 * It's tempting to think that this is a natural consequence of
17 * all the ominoes being the same size - after all, a division of
18 * anything into 7-ominoes must necessarily have all of them
19 * simply connected, because if one was not then the 1-square
20 * space in the middle could not be part of any 7-omino - but in
21 * fact, for sufficiently large k, it is perfectly possible for a
22 * k-omino to completely surround another k-omino. A simple
23 * example is this one with two 25-ominoes:
24 *
25 * +--+--+--+--+--+--+--+
26 * | |
27 * + +--+--+--+--+--+ +
28 * | | | |
29 * + + + +
30 * | | | |
31 * + + + +--+
32 * | | | |
33 * + + + +--+
34 * | | | |
35 * + + + +
36 * | | | |
37 * + +--+--+--+--+--+ +
38 * | |
39 * +--+--+--+--+--+--+--+
40 *
41 * I believe the smallest k which can manage this is 23, which I
42 * derive by considering the largest _rectangle_ a k-omino can
43 * surround. Consider: to surround an m x n rectangle, a polyomino
44 * must have 2m squares along the two m-sides of the rectangle, 2n
45 * squares along the n-sides, and fill in three of the corners. So
46 * m+n must be at most (k-3)/2. Hence, to find the largest area of
47 * such a rectangle, we must find m so as to maximise the product
48 * m((k-3)/2-m). This is achieved when m is as close as possible
49 * to half of (k-3)/2; so the largest rectangle surroundable by a
50 * k-omino is equal to floor(k'/2)*ceil(k'/2), with k'=(k-3)/2.
51 * The smallest k for which this is at least k is 23: a 23-omino
52 * can surround a 5x5 rectangle, whereas the best a 22-omino can
53 * manage is a 5x4.
54 *
55 * (I don't have a definite argument to show that a k-omino cannot
56 * surround a larger area in non-rectangular than rectangular
57 * form, but it seems intuitively obvious to me that it can't. I
58 * may update this with a more rigorous proof if I think of one.)
59 *
60 * Anyway: the point is, although constructions of this type are
61 * possible for sufficiently large k, divvy_rectangle() will never
62 * generate them. This could be considered a weakness for some
63 * purposes, in the sense that we can't generate all possible
64 * divisions. However, there are many divisions which we are
65 * highly unlikely to generate anyway, so in practice it probably
66 * isn't _too_ bad.
67 *
68 * If I wanted to fix this issue, I would have to make the rules
69 * more complicated for determining when a square can safely be
70 * _removed_ from a polyomino. Adding one becomes easier (a square
71 * may be added to a polyomino iff it is 4-adjacent to any square
72 * currently part of the polyomino, and the current test for loop
73 * formation may be dispensed with), but to determine which
74 * squares may be removed we must now resort to analysis of the
75 * overall structure of the polyomino rather than the simple local
76 * properties we can currently get away with measuring.
77 */
78
79/*
9d36cbd7 80 * Possible improvements which might cut the fail rate:
81 *
82 * - instead of picking one omino to extend in an iteration, try
83 * them all in succession (in a randomised order)
84 *
85 * - (for real rigour) instead of bfsing over ominoes, bfs over
86 * the space of possible _removed squares_. That way we aren't
87 * limited to randomly choosing a single square to remove from
88 * an omino and failing if that particular square doesn't
89 * happen to work.
90 *
4d31c526 91 * However, I don't currently think it's necessary to do either of
92 * these, because the failure rate is already low enough to be
93 * easily tolerable, under all circumstances I've been able to
94 * think of.
9d36cbd7 95 */
96
11d273f7 97#include <assert.h>
98#include <stdio.h>
99#include <stdlib.h>
100#include <stddef.h>
101
102#include "puzzles.h"
103
104/*
105 * Subroutine which implements a function used in computing both
106 * whether a square can safely be added to an omino, and whether
107 * it can safely be removed.
108 *
109 * We enumerate the eight squares 8-adjacent to this one, in
110 * cyclic order. We go round that loop and count the number of
111 * times we find a square owned by the target omino next to one
112 * not owned by it. We then return success iff that count is 2.
113 *
114 * When adding a square to an omino, this is precisely the
115 * criterion which tells us that adding the square won't leave a
a9ea89c5 116 * hole in the middle of the omino. (If it did, then things get
117 * more complicated; see above.)
11d273f7 118 *
119 * When removing a square from an omino, the _same_ criterion
120 * tells us that removing the square won't disconnect the omino.
a9ea89c5 121 * (This only works _because_ we've ensured the omino is simply
122 * connected.)
11d273f7 123 */
124static int addremcommon(int w, int h, int x, int y, int *own, int val)
125{
126 int neighbours[8];
127 int dir, count;
128
129 for (dir = 0; dir < 8; dir++) {
130 int dx = ((dir & 3) == 2 ? 0 : dir > 2 && dir < 6 ? +1 : -1);
131 int dy = ((dir & 3) == 0 ? 0 : dir < 4 ? -1 : +1);
132 int sx = x+dx, sy = y+dy;
133
134 if (sx < 0 || sx >= w || sy < 0 || sy >= h)
135 neighbours[dir] = -1; /* outside the grid */
136 else
137 neighbours[dir] = own[sy*w+sx];
138 }
139
140 /*
141 * To begin with, check 4-adjacency.
142 */
143 if (neighbours[0] != val && neighbours[2] != val &&
144 neighbours[4] != val && neighbours[6] != val)
145 return FALSE;
146
147 count = 0;
148
149 for (dir = 0; dir < 8; dir++) {
150 int next = (dir + 1) & 7;
151 int gotthis = (neighbours[dir] == val);
152 int gotnext = (neighbours[next] == val);
153
154 if (gotthis != gotnext)
155 count++;
156 }
157
158 return (count == 2);
159}
160
161/*
162 * w and h are the dimensions of the rectangle.
163 *
164 * k is the size of the required ominoes. (So k must divide w*h,
165 * of course.)
166 *
167 * The returned result is a w*h-sized dsf.
168 *
169 * In both of the above suggested use cases, the user would
170 * probably want w==h==k, but that isn't a requirement.
171 */
9d36cbd7 172static int *divvy_internal(int w, int h, int k, random_state *rs)
11d273f7 173{
174 int *order, *queue, *tmp, *own, *sizes, *addable, *removable, *retdsf;
175 int wh = w*h;
176 int i, j, n, x, y, qhead, qtail;
177
178 n = wh / k;
179 assert(wh == k*n);
180
181 order = snewn(wh, int);
182 tmp = snewn(wh, int);
183 own = snewn(wh, int);
184 sizes = snewn(n, int);
185 queue = snewn(n, int);
186 addable = snewn(wh*4, int);
187 removable = snewn(wh, int);
188
189 /*
190 * Permute the grid squares into a random order, which will be
191 * used for iterating over the grid whenever we need to search
192 * for something. This prevents directional bias and arranges
193 * for the answer to be non-deterministic.
194 */
195 for (i = 0; i < wh; i++)
196 order[i] = i;
197 shuffle(order, wh, sizeof(*order), rs);
198
199 /*
200 * Begin by choosing a starting square at random for each
201 * omino.
202 */
203 for (i = 0; i < wh; i++) {
204 own[i] = -1;
205 }
206 for (i = 0; i < n; i++) {
207 own[order[i]] = i;
208 sizes[i] = 1;
209 }
210
211 /*
212 * Now repeatedly pick a random omino which isn't already at
213 * the target size, and find a way to expand it by one. This
214 * may involve stealing a square from another omino, in which
215 * case we then re-expand that omino, forming a chain of
216 * square-stealing which terminates in an as yet unclaimed
217 * square. Hence every successful iteration around this loop
218 * causes the number of unclaimed squares to drop by one, and
219 * so the process is bounded in duration.
220 */
221 while (1) {
222
223#ifdef DIVVY_DIAGNOSTICS
224 {
225 int x, y;
226 printf("Top of loop. Current grid:\n");
227 for (y = 0; y < h; y++) {
228 for (x = 0; x < w; x++)
229 printf("%3d", own[y*w+x]);
230 printf("\n");
231 }
232 }
233#endif
234
235 /*
236 * Go over the grid and figure out which squares can
237 * safely be added to, or removed from, each omino. We
238 * don't take account of other ominoes in this process, so
239 * we will often end up knowing that a square can be
240 * poached from one omino by another.
241 *
242 * For each square, there may be up to four ominoes to
243 * which it can be added (those to which it is
244 * 4-adjacent).
245 */
246 for (y = 0; y < h; y++) {
247 for (x = 0; x < w; x++) {
248 int yx = y*w+x;
249 int curr = own[yx];
250 int dir;
251
252 if (curr < 0) {
9d36cbd7 253 removable[yx] = FALSE; /* can't remove if not owned! */
254 } else if (sizes[curr] == 1) {
255 removable[yx] = TRUE; /* can always remove a singleton */
11d273f7 256 } else {
257 /*
258 * See if this square can be removed from its
259 * omino without disconnecting it.
260 */
261 removable[yx] = addremcommon(w, h, x, y, own, curr);
262 }
263
264 for (dir = 0; dir < 4; dir++) {
265 int dx = (dir == 0 ? -1 : dir == 1 ? +1 : 0);
266 int dy = (dir == 2 ? -1 : dir == 3 ? +1 : 0);
267 int sx = x + dx, sy = y + dy;
268 int syx = sy*w+sx;
269
270 addable[yx*4+dir] = -1;
271
272 if (sx < 0 || sx >= w || sy < 0 || sy >= h)
273 continue; /* no omino here! */
274 if (own[syx] < 0)
275 continue; /* also no omino here */
276 if (own[syx] == own[yx])
277 continue; /* we already got one */
278 if (!addremcommon(w, h, x, y, own, own[syx]))
279 continue; /* would non-simply connect the omino */
280
281 addable[yx*4+dir] = own[syx];
282 }
283 }
284 }
285
286 for (i = j = 0; i < n; i++)
287 if (sizes[i] < k)
288 tmp[j++] = i;
289 if (j == 0)
290 break; /* all ominoes are complete! */
291 j = tmp[random_upto(rs, j)];
f40d37bd 292#ifdef DIVVY_DIAGNOSTICS
293 printf("Trying to extend %d\n", j);
294#endif
11d273f7 295
296 /*
297 * So we're trying to expand omino j. We breadth-first
298 * search out from j across the space of ominoes.
299 *
300 * For bfs purposes, we use two elements of tmp per omino:
301 * tmp[2*i+0] tells us which omino we got to i from, and
302 * tmp[2*i+1] numbers the grid square that omino stole
303 * from us.
304 *
305 * This requires that wh (the size of tmp) is at least 2n,
306 * i.e. k is at least 2. There would have been nothing to
307 * stop a user calling this function with k=1, but if they
308 * did then we wouldn't have got to _here_ in the code -
309 * we would have noticed above that all ominoes were
310 * already at their target sizes, and terminated :-)
311 */
312 assert(wh >= 2*n);
313 for (i = 0; i < n; i++)
314 tmp[2*i] = tmp[2*i+1] = -1;
315 qhead = qtail = 0;
316 queue[qtail++] = j;
317 tmp[2*j] = tmp[2*j+1] = -2; /* special value: `starting point' */
318
319 while (qhead < qtail) {
320 int tmpsq;
321
322 j = queue[qhead];
323
324 /*
325 * We wish to expand omino j. However, we might have
326 * got here by omino j having a square stolen from it,
327 * so first of all we must temporarily mark that
328 * square as not belonging to j, so that our adjacency
329 * calculations don't assume j _does_ belong to us.
330 */
331 tmpsq = tmp[2*j+1];
332 if (tmpsq >= 0) {
333 assert(own[tmpsq] == j);
9d36cbd7 334 own[tmpsq] = -3;
11d273f7 335 }
336
337 /*
338 * OK. Now begin by seeing if we can find any
339 * unclaimed square into which we can expand omino j.
340 * If we find one, the entire bfs terminates.
341 */
342 for (i = 0; i < wh; i++) {
343 int dir;
344
9d36cbd7 345 if (own[order[i]] != -1)
11d273f7 346 continue; /* this square is claimed */
9d36cbd7 347
348 /*
349 * Special case: if our current omino was size 1
350 * and then had a square stolen from it, it's now
351 * size zero, which means it's valid to `expand'
352 * it into _any_ unclaimed square.
353 */
354 if (sizes[j] == 1 && tmpsq >= 0)
355 break; /* got one */
356
357 /*
358 * Failing that, we must do the full test for
359 * addability.
360 */
11d273f7 361 for (dir = 0; dir < 4; dir++)
362 if (addable[order[i]*4+dir] == j) {
363 /*
364 * We know this square is addable to this
365 * omino with the grid in the state it had
366 * at the top of the loop. However, we
367 * must now check that it's _still_
368 * addable to this omino when the omino is
369 * missing a square. To do this it's only
370 * necessary to re-check addremcommon.
f40d37bd 371 */
11d273f7 372 if (!addremcommon(w, h, order[i]%w, order[i]/w,
373 own, j))
374 continue;
375 break;
376 }
377 if (dir == 4)
378 continue; /* we can't add this square to j */
9d36cbd7 379
11d273f7 380 break; /* got one! */
381 }
382 if (i < wh) {
383 i = order[i];
384
385 /*
9d36cbd7 386 * Restore the temporarily removed square _before_
387 * we start shifting ownerships about.
388 */
389 if (tmpsq >= 0)
390 own[tmpsq] = j;
391
392 /*
11d273f7 393 * We are done. We can add square i to omino j,
394 * and then backtrack along the trail in tmp
395 * moving squares between ominoes, ending up
396 * expanding our starting omino by one.
397 */
f40d37bd 398#ifdef DIVVY_DIAGNOSTICS
399 printf("(%d,%d)", i%w, i/w);
400#endif
11d273f7 401 while (1) {
402 own[i] = j;
f40d37bd 403#ifdef DIVVY_DIAGNOSTICS
404 printf(" -> %d", j);
405#endif
11d273f7 406 if (tmp[2*j] == -2)
407 break;
408 i = tmp[2*j+1];
409 j = tmp[2*j];
f40d37bd 410#ifdef DIVVY_DIAGNOSTICS
411 printf("; (%d,%d)", i%w, i/w);
412#endif
11d273f7 413 }
f40d37bd 414#ifdef DIVVY_DIAGNOSTICS
415 printf("\n");
416#endif
11d273f7 417
418 /*
419 * Increment the size of the starting omino.
420 */
421 sizes[j]++;
422
423 /*
424 * Terminate the bfs loop.
425 */
426 break;
427 }
428
429 /*
430 * If we get here, we haven't been able to expand
431 * omino j into an unclaimed square. So now we begin
432 * to investigate expanding it into squares which are
433 * claimed by ominoes the bfs has not yet visited.
434 */
435 for (i = 0; i < wh; i++) {
436 int dir, nj;
437
438 nj = own[order[i]];
439 if (nj < 0 || tmp[2*nj] != -1)
440 continue; /* unclaimed, or owned by wrong omino */
441 if (!removable[order[i]])
442 continue; /* its omino won't let it go */
443
444 for (dir = 0; dir < 4; dir++)
445 if (addable[order[i]*4+dir] == j) {
446 /*
447 * As above, re-check addremcommon.
448 */
449 if (!addremcommon(w, h, order[i]%w, order[i]/w,
450 own, j))
451 continue;
452
453 /*
454 * We have found a square we can use to
455 * expand omino j, at the expense of the
456 * as-yet unvisited omino nj. So add this
457 * to the bfs queue.
458 */
459 assert(qtail < n);
460 queue[qtail++] = nj;
461 tmp[2*nj] = j;
462 tmp[2*nj+1] = order[i];
463
464 /*
465 * Now terminate the loop over dir, to
466 * ensure we don't accidentally add the
467 * same omino twice to the queue.
468 */
469 break;
470 }
471 }
472
473 /*
474 * Restore the temporarily removed square.
475 */
476 if (tmpsq >= 0)
477 own[tmpsq] = j;
478
479 /*
480 * Advance the queue head.
481 */
482 qhead++;
483 }
484
485 if (qhead == qtail) {
486 /*
487 * We have finished the bfs and not found any way to
488 * expand omino j. Panic, and return failure.
489 *
490 * FIXME: or should we loop over all ominoes before we
491 * give up?
492 */
f40d37bd 493#ifdef DIVVY_DIAGNOSTICS
494 printf("FAIL!\n");
495#endif
11d273f7 496 retdsf = NULL;
497 goto cleanup;
498 }
499 }
500
f40d37bd 501#ifdef DIVVY_DIAGNOSTICS
502 {
503 int x, y;
504 printf("SUCCESS! Final grid:\n");
505 for (y = 0; y < h; y++) {
506 for (x = 0; x < w; x++)
507 printf("%3d", own[y*w+x]);
508 printf("\n");
509 }
510 }
511#endif
512
11d273f7 513 /*
514 * Construct the output dsf.
515 */
516 for (i = 0; i < wh; i++) {
517 assert(own[i] >= 0 && own[i] < n);
518 tmp[own[i]] = i;
519 }
520 retdsf = snew_dsf(wh);
521 for (i = 0; i < wh; i++) {
522 dsf_merge(retdsf, i, tmp[own[i]]);
523 }
524
525 /*
526 * Construct the output dsf a different way, to verify that
527 * the ominoes really are k-ominoes and we haven't
528 * accidentally split one into two disconnected pieces.
529 */
530 dsf_init(tmp, wh);
531 for (y = 0; y < h; y++)
532 for (x = 0; x+1 < w; x++)
533 if (own[y*w+x] == own[y*w+(x+1)])
534 dsf_merge(tmp, y*w+x, y*w+(x+1));
535 for (x = 0; x < w; x++)
536 for (y = 0; y+1 < h; y++)
537 if (own[y*w+x] == own[(y+1)*w+x])
538 dsf_merge(tmp, y*w+x, (y+1)*w+x);
539 for (i = 0; i < wh; i++) {
540 j = dsf_canonify(retdsf, i);
541 assert(dsf_canonify(tmp, j) == dsf_canonify(tmp, i));
542 }
543
544 cleanup:
545
546 /*
547 * Free our temporary working space.
548 */
549 sfree(order);
550 sfree(tmp);
551 sfree(own);
552 sfree(sizes);
553 sfree(queue);
554 sfree(addable);
555 sfree(removable);
556
557 /*
558 * And we're done.
559 */
560 return retdsf;
561}
562
563#ifdef TESTMODE
9d36cbd7 564static int fail_counter = 0;
565#endif
566
567int *divvy_rectangle(int w, int h, int k, random_state *rs)
568{
569 int *ret;
570
571 do {
572 ret = divvy_internal(w, h, k, rs);
573
574#ifdef TESTMODE
575 if (!ret)
576 fail_counter++;
577#endif
578
579 } while (!ret);
580
581 return ret;
582}
583
584#ifdef TESTMODE
11d273f7 585
586/*
587 * gcc -g -O0 -DTESTMODE -I.. -o divvy divvy.c ../random.c ../malloc.c ../dsf.c ../misc.c ../nullfe.c
588 *
589 * or to debug
590 *
591 * gcc -g -O0 -DDIVVY_DIAGNOSTICS -DTESTMODE -I.. -o divvy divvy.c ../random.c ../malloc.c ../dsf.c ../misc.c ../nullfe.c
592 */
593
594int main(int argc, char **argv)
595{
596 int *dsf;
9d36cbd7 597 int i;
11d273f7 598 int w = 9, h = 4, k = 6, tries = 100;
599 random_state *rs;
600
601 rs = random_new("123456", 6);
602
603 if (argc > 1)
604 w = atoi(argv[1]);
605 if (argc > 2)
606 h = atoi(argv[2]);
607 if (argc > 3)
608 k = atoi(argv[3]);
609 if (argc > 4)
610 tries = atoi(argv[4]);
611
11d273f7 612 for (i = 0; i < tries; i++) {
9d36cbd7 613 int x, y;
11d273f7 614
9d36cbd7 615 dsf = divvy_rectangle(w, h, k, rs);
616 assert(dsf);
617
618 for (y = 0; y <= 2*h; y++) {
619 for (x = 0; x <= 2*w; x++) {
620 int miny = y/2 - 1, maxy = y/2;
621 int minx = x/2 - 1, maxx = x/2;
622 int classes[4], tx, ty;
623 for (ty = 0; ty < 2; ty++)
624 for (tx = 0; tx < 2; tx++) {
625 int cx = minx+tx, cy = miny+ty;
626 if (cx < 0 || cx >= w || cy < 0 || cy >= h)
627 classes[ty*2+tx] = -1;
11d273f7 628 else
9d36cbd7 629 classes[ty*2+tx] = dsf_canonify(dsf, cy*w+cx);
11d273f7 630 }
9d36cbd7 631 switch (y%2 * 2 + x%2) {
632 case 0: /* corner */
633 /*
634 * Cases for the corner:
635 *
636 * - if all four surrounding squares belong
637 * to the same omino, we print a space.
638 *
639 * - if the top two are the same and the
640 * bottom two are the same, we print a
641 * horizontal line.
642 *
643 * - if the left two are the same and the
644 * right two are the same, we print a
645 * vertical line.
646 *
647 * - otherwise, we print a cross.
648 */
649 if (classes[0] == classes[1] &&
650 classes[1] == classes[2] &&
651 classes[2] == classes[3])
652 printf(" ");
653 else if (classes[0] == classes[1] &&
654 classes[2] == classes[3])
655 printf("-");
656 else if (classes[0] == classes[2] &&
657 classes[1] == classes[3])
658 printf("|");
659 else
660 printf("+");
661 break;
662 case 1: /* horiz edge */
663 if (classes[1] == classes[3])
664 printf(" ");
665 else
666 printf("--");
667 break;
668 case 2: /* vert edge */
669 if (classes[2] == classes[3])
670 printf(" ");
671 else
672 printf("|");
673 break;
674 case 3: /* square centre */
675 printf(" ");
676 break;
11d273f7 677 }
11d273f7 678 }
679 printf("\n");
11d273f7 680 }
9d36cbd7 681 printf("\n");
682 sfree(dsf);
11d273f7 683 }
684
9d36cbd7 685 printf("%d retries needed for %d successes\n", fail_counter, tries);
11d273f7 686
687 return 0;
688}
689
690#endif