An option to enable a debugging mode for the BFS.
[sgt/puzzles] / unfinished / numgame.c
CommitLineData
f278dcf4 1/*
2 * This program implements a breadth-first search which
3 * exhaustively solves the Countdown numbers game, and related
4 * games with slightly different rule sets such as `Flippo'.
5 *
6 * Currently it is simply a standalone command-line utility to
7 * which you provide a set of numbers and it tells you everything
8 * it can make together with how many different ways it can be
9 * made. I would like ultimately to turn it into the generator for
10 * a Puzzles puzzle, but I haven't even started on writing a
11 * Puzzles user interface yet.
12 */
13
14/*
15 * TODO:
16 *
17 * - start thinking about difficulty ratings
18 * + anything involving associative operations will be flagged
19 * as many-paths because of the associative options (e.g.
20 * 2*3*4 can be (2*3)*4 or 2*(3*4), or indeed (2*4)*3). This
21 * is probably a _good_ thing, since those are unusually
22 * easy.
23 * + tree-structured calculations ((a*b)/(c+d)) have multiple
24 * paths because the independent branches of the tree can be
25 * evaluated in either order, whereas straight-line
26 * calculations with no branches will be considered easier.
27 * Can we do anything about this? It's certainly not clear to
28 * me that tree-structure calculations are _easier_, although
29 * I'm also not convinced they're harder.
30 * + I think for a realistic difficulty assessment we must also
31 * consider the `obviousness' of the arithmetic operations in
32 * some heuristic sense, and also (in Countdown) how many
33 * numbers ended up being used.
34 * - actually try some generations
35 * - at this point we're probably ready to start on the Puzzles
36 * integration.
37 */
38
39#include <stdio.h>
ed35622c 40#include <string.h>
f278dcf4 41#include <limits.h>
42#include <assert.h>
ed35622c 43#include <math.h>
f278dcf4 44
45#include "puzzles.h"
46#include "tree234.h"
47
48/*
49 * To search for numbers we can make, we employ a breadth-first
50 * search across the space of sets of input numbers. That is, for
51 * example, we start with the set (3,6,25,50,75,100); we apply
52 * moves which involve combining two numbers (e.g. adding the 50
53 * and the 75 takes us to the set (3,6,25,100,125); and then we see
54 * if we ever end up with a set containing (say) 952.
55 *
56 * If the rules are changed so that all the numbers must be used,
57 * this is easy to adjust to: we simply see if we end up with a set
58 * containing _only_ (say) 952.
59 *
60 * Obviously, we can vary the rules about permitted arithmetic
61 * operations simply by altering the set of valid moves in the bfs.
62 * However, there's one common rule in this sort of puzzle which
63 * takes a little more thought, and that's _concatenation_. For
64 * example, if you are given (say) four 4s and required to make 10,
65 * you are permitted to combine two of the 4s into a 44 to begin
66 * with, making (44-4)/4 = 10. However, you are generally not
67 * allowed to concatenate two numbers that _weren't_ both in the
68 * original input set (you couldn't multiply two 4s to get 16 and
69 * then concatenate a 4 on to it to make 164), so concatenation is
70 * not an operation which is valid in all situations.
71 *
72 * We could enforce this restriction by storing a flag alongside
73 * each number indicating whether or not it's an original number;
74 * the rules being that concatenation of two numbers is only valid
75 * if they both have the original flag, and that its output _also_
76 * has the original flag (so that you can concatenate three 4s into
77 * a 444), but that applying any other arithmetic operation clears
78 * the original flag on the output. However, we can get marginally
79 * simpler than that by observing that since concatenation has to
80 * happen to a number before any other operation, we can simply
81 * place all the concatenations at the start of the search. In
82 * other words, we have a global flag on an entire number _set_
83 * which indicates whether we are still permitted to perform
84 * concatenations; if so, we can concatenate any of the numbers in
85 * that set. Performing any other operation clears the flag.
86 */
87
88#define SETFLAG_CONCAT 1 /* we can do concatenation */
89
90struct sets;
91
ed35622c 92struct ancestor {
93 struct set *prev; /* index of ancestor set in set list */
94 unsigned char pa, pb, po, pr; /* operation that got here from prev */
95};
96
f278dcf4 97struct set {
98 int *numbers; /* rationals stored as n,d pairs */
99 short nnumbers; /* # of rationals, so half # of ints */
100 short flags; /* SETFLAG_CONCAT only, at present */
f278dcf4 101 int npaths; /* number of ways to reach this set */
ed35622c 102 struct ancestor a; /* primary ancestor */
103 struct ancestor *as; /* further ancestors, if we care */
104 int nas, assize;
f278dcf4 105};
106
107struct output {
108 int number;
109 struct set *set;
110 int index; /* which number in the set is it? */
111 int npaths; /* number of ways to reach this */
112};
113
114#define SETLISTLEN 1024
115#define NUMBERLISTLEN 32768
116#define OUTPUTLISTLEN 1024
117struct operation;
118struct sets {
119 struct set **setlists;
120 int nsets, nsetlists, setlistsize;
121 tree234 *settree;
122 int **numberlists;
123 int nnumbers, nnumberlists, numberlistsize;
124 struct output **outputlists;
125 int noutputs, noutputlists, outputlistsize;
126 tree234 *outputtree;
127 const struct operation *const *ops;
128};
129
130#define OPFLAG_NEEDS_CONCAT 1
131#define OPFLAG_KEEPS_CONCAT 2
ed35622c 132#define OPFLAG_UNARY 4
133#define OPFLAG_UNARYPFX 8
f278dcf4 134
135struct operation {
136 /*
137 * Most operations should be shown in the output working, but
138 * concatenation should not; we just take the result of the
139 * concatenation and assume that it's obvious how it was
140 * derived.
141 */
142 int display;
143
144 /*
91623748 145 * Text display of the operator, in expressions and for
146 * debugging respectively.
f278dcf4 147 */
91623748 148 char *text, *dbgtext;
f278dcf4 149
150 /*
151 * Flags dictating when the operator can be applied.
152 */
153 int flags;
154
155 /*
156 * Priority of the operator (for avoiding unnecessary
157 * parentheses when formatting it into a string).
158 */
159 int priority;
160
161 /*
162 * Associativity of the operator. Bit 0 means we need parens
163 * when the left operand of one of these operators is another
164 * instance of it, e.g. (2^3)^4. Bit 1 means we need parens
165 * when the right operand is another instance of the same
166 * operator, e.g. 2-(3-4). Thus:
167 *
168 * - this field is 0 for a fully associative operator, since
169 * we never need parens.
170 * - it's 1 for a right-associative operator.
171 * - it's 2 for a left-associative operator.
172 * - it's 3 for a _non_-associative operator (which always
173 * uses parens just to be sure).
174 */
175 int assoc;
176
177 /*
178 * Whether the operator is commutative. Saves time in the
179 * search if we don't have to try it both ways round.
180 */
181 int commutes;
182
183 /*
184 * Function which implements the operator. Returns TRUE on
185 * success, FALSE on failure. Takes two rationals and writes
186 * out a third.
187 */
188 int (*perform)(int *a, int *b, int *output);
189};
190
191struct rules {
192 const struct operation *const *ops;
193 int use_all;
194};
195
196#define MUL(r, a, b) do { \
197 (r) = (a) * (b); \
198 if ((b) && (a) && (r) / (b) != (a)) return FALSE; \
199} while (0)
200
201#define ADD(r, a, b) do { \
202 (r) = (a) + (b); \
203 if ((a) > 0 && (b) > 0 && (r) < 0) return FALSE; \
204 if ((a) < 0 && (b) < 0 && (r) > 0) return FALSE; \
205} while (0)
206
207#define OUT(output, n, d) do { \
208 int g = gcd((n),(d)); \
ed35622c 209 if (g < 0) g = -g; \
f278dcf4 210 if ((d) < 0) g = -g; \
ed35622c 211 if (g == -1 && (n) < -INT_MAX) return FALSE; \
212 if (g == -1 && (d) < -INT_MAX) return FALSE; \
f278dcf4 213 (output)[0] = (n)/g; \
214 (output)[1] = (d)/g; \
215 assert((output)[1] > 0); \
216} while (0)
217
218static int gcd(int x, int y)
219{
220 while (x != 0 && y != 0) {
221 int t = x;
222 x = y;
223 y = t % y;
224 }
225
226 return abs(x + y); /* i.e. whichever one isn't zero */
227}
228
229static int perform_add(int *a, int *b, int *output)
230{
231 int at, bt, tn, bn;
232 /*
233 * a0/a1 + b0/b1 = (a0*b1 + b0*a1) / (a1*b1)
234 */
235 MUL(at, a[0], b[1]);
236 MUL(bt, b[0], a[1]);
237 ADD(tn, at, bt);
238 MUL(bn, a[1], b[1]);
239 OUT(output, tn, bn);
240 return TRUE;
241}
242
243static int perform_sub(int *a, int *b, int *output)
244{
245 int at, bt, tn, bn;
246 /*
247 * a0/a1 - b0/b1 = (a0*b1 - b0*a1) / (a1*b1)
248 */
249 MUL(at, a[0], b[1]);
250 MUL(bt, b[0], a[1]);
251 ADD(tn, at, -bt);
252 MUL(bn, a[1], b[1]);
253 OUT(output, tn, bn);
254 return TRUE;
255}
256
257static int perform_mul(int *a, int *b, int *output)
258{
259 int tn, bn;
260 /*
261 * a0/a1 * b0/b1 = (a0*b0) / (a1*b1)
262 */
263 MUL(tn, a[0], b[0]);
264 MUL(bn, a[1], b[1]);
265 OUT(output, tn, bn);
266 return TRUE;
267}
268
269static int perform_div(int *a, int *b, int *output)
270{
271 int tn, bn;
272
273 /*
274 * Division by zero is outlawed.
275 */
276 if (b[0] == 0)
277 return FALSE;
278
279 /*
280 * a0/a1 / b0/b1 = (a0*b1) / (a1*b0)
281 */
282 MUL(tn, a[0], b[1]);
283 MUL(bn, a[1], b[0]);
284 OUT(output, tn, bn);
285 return TRUE;
286}
287
288static int perform_exact_div(int *a, int *b, int *output)
289{
290 int tn, bn;
291
292 /*
293 * Division by zero is outlawed.
294 */
295 if (b[0] == 0)
296 return FALSE;
297
298 /*
299 * a0/a1 / b0/b1 = (a0*b1) / (a1*b0)
300 */
301 MUL(tn, a[0], b[1]);
302 MUL(bn, a[1], b[0]);
303 OUT(output, tn, bn);
304
305 /*
306 * Exact division means we require the result to be an integer.
307 */
308 return (output[1] == 1);
309}
310
311static int perform_concat(int *a, int *b, int *output)
312{
313 int t1, t2, p10;
314
315 /*
ed35622c 316 * We can't concatenate anything which isn't a non-negative
317 * integer.
f278dcf4 318 */
ed35622c 319 if (a[1] != 1 || b[1] != 1 || a[0] < 0 || b[0] < 0)
f278dcf4 320 return FALSE;
321
322 /*
323 * For concatenation, we can safely assume leading zeroes
324 * aren't an issue. It isn't clear whether they `should' be
325 * allowed, but it turns out not to matter: concatenating a
326 * leading zero on to a number in order to harmlessly get rid
327 * of the zero is never necessary because unwanted zeroes can
328 * be disposed of by adding them to something instead. So we
329 * disallow them always.
330 *
331 * The only other possibility is that you might want to
332 * concatenate a leading zero on to something and then
333 * concatenate another non-zero digit on to _that_ (to make,
334 * for example, 106); but that's also unnecessary, because you
335 * can make 106 just as easily by concatenating the 0 on to the
336 * _end_ of the 1 first.
337 */
338 if (a[0] == 0)
339 return FALSE;
340
341 /*
342 * Find the smallest power of ten strictly greater than b. This
343 * is the power of ten by which we'll multiply a.
344 *
345 * Special case: we must multiply a by at least 10, even if b
346 * is zero.
347 */
348 p10 = 10;
349 while (p10 <= (INT_MAX/10) && p10 <= b[0])
350 p10 *= 10;
351 if (p10 > INT_MAX/10)
352 return FALSE; /* integer overflow */
353 MUL(t1, p10, a[0]);
354 ADD(t2, t1, b[0]);
355 OUT(output, t2, 1);
356 return TRUE;
357}
358
ed35622c 359#define IPOW(ret, x, y) do { \
360 int ipow_limit = (y); \
361 if ((x) == 1 || (x) == 0) ipow_limit = 1; \
362 else if ((x) == -1) ipow_limit &= 1; \
363 (ret) = 1; \
364 while (ipow_limit-- > 0) { \
365 int tmp; \
366 MUL(tmp, ret, x); \
367 ret = tmp; \
368 } \
369} while (0)
370
371static int perform_exp(int *a, int *b, int *output)
372{
373 int an, ad, xn, xd, limit, t, i;
374
375 /*
376 * Exponentiation is permitted if the result is rational. This
377 * means that:
378 *
379 * - first we see whether we can take the (denominator-of-b)th
380 * root of a and get a rational; if not, we give up.
381 *
382 * - then we do take that root of a
383 *
384 * - then we multiply by itself (numerator-of-b) times.
385 */
386 if (b[1] > 1) {
387 an = 0.5 + pow(a[0], 1.0/b[1]);
388 ad = 0.5 + pow(a[1], 1.0/b[1]);
389 IPOW(xn, an, b[1]);
390 IPOW(xd, ad, b[1]);
391 if (xn != a[0] || xd != a[1])
392 return FALSE;
393 } else {
394 an = a[0];
395 ad = a[1];
396 }
397 if (b[0] >= 0) {
398 IPOW(xn, an, b[0]);
399 IPOW(xd, ad, b[0]);
400 } else {
401 IPOW(xd, an, -b[0]);
402 IPOW(xn, ad, -b[0]);
403 }
404 if (xd == 0)
405 return FALSE;
406
407 OUT(output, xn, xd);
408 return TRUE;
409}
410
411static int perform_factorial(int *a, int *b, int *output)
412{
413 int ret, t, i;
414
415 /*
416 * Factorials of non-negative integers are permitted.
417 */
418 if (a[1] != 1 || a[0] < 0)
419 return FALSE;
420
91623748 421 /*
422 * However, a special case: we don't take a factorial of
423 * anything which would thereby remain the same.
424 */
425 if (a[0] == 1 || a[0] == 2)
426 return FALSE;
427
ed35622c 428 ret = 1;
429 for (i = 1; i <= a[0]; i++) {
430 MUL(t, ret, i);
431 ret = t;
432 }
433
434 OUT(output, ret, 1);
435 return TRUE;
436}
437
f278dcf4 438const static struct operation op_add = {
91623748 439 TRUE, "+", "+", 0, 10, 0, TRUE, perform_add
f278dcf4 440};
441const static struct operation op_sub = {
91623748 442 TRUE, "-", "-", 0, 10, 2, FALSE, perform_sub
f278dcf4 443};
444const static struct operation op_mul = {
91623748 445 TRUE, "*", "*", 0, 20, 0, TRUE, perform_mul
f278dcf4 446};
447const static struct operation op_div = {
91623748 448 TRUE, "/", "/", 0, 20, 2, FALSE, perform_div
f278dcf4 449};
450const static struct operation op_xdiv = {
91623748 451 TRUE, "/", "/", 0, 20, 2, FALSE, perform_exact_div
f278dcf4 452};
453const static struct operation op_concat = {
91623748 454 FALSE, "", "concat", OPFLAG_NEEDS_CONCAT | OPFLAG_KEEPS_CONCAT,
f278dcf4 455 1000, 0, FALSE, perform_concat
456};
ed35622c 457const static struct operation op_exp = {
91623748 458 TRUE, "^", "^", 0, 30, 1, FALSE, perform_exp
ed35622c 459};
460const static struct operation op_factorial = {
91623748 461 TRUE, "!", "!", OPFLAG_UNARY, 40, 0, FALSE, perform_factorial
ed35622c 462};
f278dcf4 463
464/*
465 * In Countdown, divisions resulting in fractions are disallowed.
466 * http://www.askoxford.com/wordgames/countdown/rules/
467 */
468const static struct operation *const ops_countdown[] = {
469 &op_add, &op_mul, &op_sub, &op_xdiv, NULL
470};
471const static struct rules rules_countdown = {
472 ops_countdown, FALSE
473};
474
475/*
476 * A slightly different rule set which handles the reasonably well
477 * known puzzle of making 24 using two 3s and two 8s. For this we
478 * need rational rather than integer division.
479 */
480const static struct operation *const ops_3388[] = {
481 &op_add, &op_mul, &op_sub, &op_div, NULL
482};
483const static struct rules rules_3388 = {
484 ops_3388, TRUE
485};
486
487/*
488 * A still more permissive rule set usable for the four-4s problem
489 * and similar things. Permits concatenation.
490 */
491const static struct operation *const ops_four4s[] = {
492 &op_add, &op_mul, &op_sub, &op_div, &op_concat, NULL
493};
494const static struct rules rules_four4s = {
495 ops_four4s, TRUE
496};
497
ed35622c 498/*
499 * The most permissive ruleset I can think of. Permits
500 * exponentiation, and also silly unary operators like factorials.
501 */
502const static struct operation *const ops_anythinggoes[] = {
503 &op_add, &op_mul, &op_sub, &op_div, &op_concat, &op_exp, &op_factorial, NULL
504};
505const static struct rules rules_anythinggoes = {
506 ops_anythinggoes, TRUE
507};
508
f278dcf4 509#define ratcmp(a,op,b) ( (long long)(a)[0] * (b)[1] op \
510 (long long)(b)[0] * (a)[1] )
511
512static int addtoset(struct set *set, int newnumber[2])
513{
514 int i, j;
515
516 /* Find where we want to insert the new number */
517 for (i = 0; i < set->nnumbers &&
518 ratcmp(set->numbers+2*i, <, newnumber); i++);
519
520 /* Move everything else up */
521 for (j = set->nnumbers; j > i; j--) {
522 set->numbers[2*j] = set->numbers[2*j-2];
523 set->numbers[2*j+1] = set->numbers[2*j-1];
524 }
525
526 /* Insert the new number */
527 set->numbers[2*i] = newnumber[0];
528 set->numbers[2*i+1] = newnumber[1];
529
530 set->nnumbers++;
531
532 return i;
533}
534
535#define ensure(array, size, newlen, type) do { \
536 if ((newlen) > (size)) { \
537 (size) = (newlen) + 512; \
538 (array) = sresize((array), (size), type); \
539 } \
540} while (0)
541
542static int setcmp(void *av, void *bv)
543{
544 struct set *a = (struct set *)av;
545 struct set *b = (struct set *)bv;
546 int i;
547
548 if (a->nnumbers < b->nnumbers)
549 return -1;
550 else if (a->nnumbers > b->nnumbers)
551 return +1;
552
553 if (a->flags < b->flags)
554 return -1;
555 else if (a->flags > b->flags)
556 return +1;
557
558 for (i = 0; i < a->nnumbers; i++) {
559 if (ratcmp(a->numbers+2*i, <, b->numbers+2*i))
560 return -1;
561 else if (ratcmp(a->numbers+2*i, >, b->numbers+2*i))
562 return +1;
563 }
564
565 return 0;
566}
567
568static int outputcmp(void *av, void *bv)
569{
570 struct output *a = (struct output *)av;
571 struct output *b = (struct output *)bv;
572
573 if (a->number < b->number)
574 return -1;
575 else if (a->number > b->number)
576 return +1;
577
578 return 0;
579}
580
581static int outputfindcmp(void *av, void *bv)
582{
583 int *a = (int *)av;
584 struct output *b = (struct output *)bv;
585
586 if (*a < b->number)
587 return -1;
588 else if (*a > b->number)
589 return +1;
590
591 return 0;
592}
593
ed35622c 594static void addset(struct sets *s, struct set *set, int multiple,
595 struct set *prev, int pa, int po, int pb, int pr)
f278dcf4 596{
597 struct set *s2;
598 int npaths = (prev ? prev->npaths : 1);
599
600 assert(set == s->setlists[s->nsets / SETLISTLEN] + s->nsets % SETLISTLEN);
601 s2 = add234(s->settree, set);
602 if (s2 == set) {
603 /*
604 * New set added to the tree.
605 */
ed35622c 606 set->a.prev = prev;
607 set->a.pa = pa;
608 set->a.po = po;
609 set->a.pb = pb;
610 set->a.pr = pr;
f278dcf4 611 set->npaths = npaths;
612 s->nsets++;
613 s->nnumbers += 2 * set->nnumbers;
ed35622c 614 set->as = NULL;
615 set->nas = set->assize = 0;
f278dcf4 616 } else {
617 /*
ed35622c 618 * Rediscovered an existing set. Update its npaths.
f278dcf4 619 */
620 s2->npaths += npaths;
ed35622c 621 /*
622 * And optionally enter it as an additional ancestor.
623 */
624 if (multiple) {
625 if (s2->nas >= s2->assize) {
626 s2->assize = s2->nas * 3 / 2 + 4;
627 s2->as = sresize(s2->as, s2->assize, struct ancestor);
628 }
629 s2->as[s2->nas].prev = prev;
630 s2->as[s2->nas].pa = pa;
631 s2->as[s2->nas].po = po;
632 s2->as[s2->nas].pb = pb;
633 s2->as[s2->nas].pr = pr;
634 s2->nas++;
635 }
f278dcf4 636 }
637}
638
639static struct set *newset(struct sets *s, int nnumbers, int flags)
640{
641 struct set *sn;
642
643 ensure(s->setlists, s->setlistsize, s->nsets/SETLISTLEN+1, struct set *);
644 while (s->nsetlists <= s->nsets / SETLISTLEN)
645 s->setlists[s->nsetlists++] = snewn(SETLISTLEN, struct set);
646 sn = s->setlists[s->nsets / SETLISTLEN] + s->nsets % SETLISTLEN;
647
648 if (s->nnumbers + nnumbers * 2 > s->nnumberlists * NUMBERLISTLEN)
649 s->nnumbers = s->nnumberlists * NUMBERLISTLEN;
650 ensure(s->numberlists, s->numberlistsize,
651 s->nnumbers/NUMBERLISTLEN+1, int *);
652 while (s->nnumberlists <= s->nnumbers / NUMBERLISTLEN)
653 s->numberlists[s->nnumberlists++] = snewn(NUMBERLISTLEN, int);
654 sn->numbers = s->numberlists[s->nnumbers / NUMBERLISTLEN] +
655 s->nnumbers % NUMBERLISTLEN;
656
657 /*
658 * Start the set off empty.
659 */
660 sn->nnumbers = 0;
661
662 sn->flags = flags;
663
664 return sn;
665}
666
667static int addoutput(struct sets *s, struct set *ss, int index, int *n)
668{
669 struct output *o, *o2;
670
671 /*
672 * Target numbers are always integers.
673 */
674 if (ss->numbers[2*index+1] != 1)
675 return FALSE;
676
677 ensure(s->outputlists, s->outputlistsize, s->noutputs/OUTPUTLISTLEN+1,
678 struct output *);
679 while (s->noutputlists <= s->noutputs / OUTPUTLISTLEN)
680 s->outputlists[s->noutputlists++] = snewn(OUTPUTLISTLEN,
681 struct output);
682 o = s->outputlists[s->noutputs / OUTPUTLISTLEN] +
683 s->noutputs % OUTPUTLISTLEN;
684
685 o->number = ss->numbers[2*index];
686 o->set = ss;
687 o->index = index;
688 o->npaths = ss->npaths;
689 o2 = add234(s->outputtree, o);
690 if (o2 != o) {
691 o2->npaths += o->npaths;
692 } else {
693 s->noutputs++;
694 }
695 *n = o->number;
696 return TRUE;
697}
698
699static struct sets *do_search(int ninputs, int *inputs,
ed35622c 700 const struct rules *rules, int *target,
91623748 701 int debug, int multiple)
f278dcf4 702{
703 struct sets *s;
704 struct set *sn;
705 int qpos, i;
706 const struct operation *const *ops = rules->ops;
707
708 s = snew(struct sets);
709 s->setlists = NULL;
710 s->nsets = s->nsetlists = s->setlistsize = 0;
711 s->numberlists = NULL;
712 s->nnumbers = s->nnumberlists = s->numberlistsize = 0;
713 s->outputlists = NULL;
714 s->noutputs = s->noutputlists = s->outputlistsize = 0;
715 s->settree = newtree234(setcmp);
716 s->outputtree = newtree234(outputcmp);
717 s->ops = ops;
718
719 /*
720 * Start with the input set.
721 */
722 sn = newset(s, ninputs, SETFLAG_CONCAT);
723 for (i = 0; i < ninputs; i++) {
724 int newnumber[2];
725 newnumber[0] = inputs[i];
726 newnumber[1] = 1;
727 addtoset(sn, newnumber);
728 }
ed35622c 729 addset(s, sn, multiple, NULL, 0, 0, 0, 0);
f278dcf4 730
731 /*
732 * Now perform the breadth-first search: keep looping over sets
733 * until we run out of steam.
734 */
735 qpos = 0;
736 while (qpos < s->nsets) {
737 struct set *ss = s->setlists[qpos / SETLISTLEN] + qpos % SETLISTLEN;
738 struct set *sn;
739 int i, j, k, m;
740
91623748 741 if (debug) {
742 int i;
743 printf("processing set:");
744 for (i = 0; i < ss->nnumbers; i++) {
745 printf(" %d", ss->numbers[2*i]);
746 if (ss->numbers[2*i+1] != 1)
747 printf("/%d", ss->numbers[2*i]+1);
748 }
749 printf("\n");
750 }
751
f278dcf4 752 /*
753 * Record all the valid output numbers in this state. We
754 * can always do this if there's only one number in the
755 * state; otherwise, we can only do it if we aren't
756 * required to use all the numbers in coming to our answer.
757 */
758 if (ss->nnumbers == 1 || !rules->use_all) {
759 for (i = 0; i < ss->nnumbers; i++) {
760 int n;
761
762 if (addoutput(s, ss, i, &n) && target && n == *target)
763 return s;
764 }
765 }
766
767 /*
768 * Try every possible operation from this state.
769 */
770 for (k = 0; ops[k] && ops[k]->perform; k++) {
771 if ((ops[k]->flags & OPFLAG_NEEDS_CONCAT) &&
772 !(ss->flags & SETFLAG_CONCAT))
773 continue; /* can't use this operation here */
774 for (i = 0; i < ss->nnumbers; i++) {
ed35622c 775 int jlimit = (ops[k]->flags & OPFLAG_UNARY ? 1 : ss->nnumbers);
776 for (j = 0; j < jlimit; j++) {
f278dcf4 777 int n[2];
ed35622c 778 int pa, po, pb, pr;
f278dcf4 779
ed35622c 780 if (!(ops[k]->flags & OPFLAG_UNARY)) {
781 if (i == j)
782 continue; /* can't combine a number with itself */
783 if (i > j && ops[k]->commutes)
784 continue; /* no need to do this both ways round */
785 }
f278dcf4 786 if (!ops[k]->perform(ss->numbers+2*i, ss->numbers+2*j, n))
787 continue; /* operation failed */
788
789 sn = newset(s, ss->nnumbers-1, ss->flags);
790
791 if (!(ops[k]->flags & OPFLAG_KEEPS_CONCAT))
792 sn->flags &= ~SETFLAG_CONCAT;
793
794 for (m = 0; m < ss->nnumbers; m++) {
ed35622c 795 if (m == i || (!(ops[k]->flags & OPFLAG_UNARY) &&
796 m == j))
f278dcf4 797 continue;
798 sn->numbers[2*sn->nnumbers] = ss->numbers[2*m];
799 sn->numbers[2*sn->nnumbers + 1] = ss->numbers[2*m + 1];
800 sn->nnumbers++;
801 }
ed35622c 802 pa = i;
803 if (ops[k]->flags & OPFLAG_UNARY)
804 pb = sn->nnumbers+10;
805 else
806 pb = j;
807 po = k;
808 pr = addtoset(sn, n);
809 addset(s, sn, multiple, ss, pa, po, pb, pr);
91623748 810 if (debug) {
811 int i;
812 printf(" %d %s %d ->", pa, ops[po]->dbgtext, pb);
813 for (i = 0; i < sn->nnumbers; i++) {
814 printf(" %d", sn->numbers[2*i]);
815 if (sn->numbers[2*i+1] != 1)
816 printf("/%d", sn->numbers[2*i]+1);
817 }
818 printf("\n");
819 }
f278dcf4 820 }
821 }
822 }
823
824 qpos++;
825 }
826
827 return s;
828}
829
830static void free_sets(struct sets *s)
831{
832 int i;
833
834 freetree234(s->settree);
835 freetree234(s->outputtree);
836 for (i = 0; i < s->nsetlists; i++)
837 sfree(s->setlists[i]);
838 sfree(s->setlists);
839 for (i = 0; i < s->nnumberlists; i++)
840 sfree(s->numberlists[i]);
841 sfree(s->numberlists);
842 for (i = 0; i < s->noutputlists; i++)
843 sfree(s->outputlists[i]);
844 sfree(s->outputlists);
845 sfree(s);
846}
847
848/*
ed35622c 849 * Print a text formula for producing a given output.
f278dcf4 850 */
ed35622c 851void print_recurse(struct sets *s, struct set *ss, int pathindex, int index,
852 int priority, int assoc, int child);
853void print_recurse_inner(struct sets *s, struct set *ss,
854 struct ancestor *a, int pathindex, int index,
855 int priority, int assoc, int child)
f278dcf4 856{
ed35622c 857 if (a->prev && index != a->pr) {
f278dcf4 858 int pi;
859
860 /*
861 * This number was passed straight down from this set's
862 * predecessor. Find its index in the previous set and
863 * recurse to there.
864 */
865 pi = index;
ed35622c 866 assert(pi != a->pr);
867 if (pi > a->pr)
f278dcf4 868 pi--;
ed35622c 869 if (pi >= min(a->pa, a->pb)) {
f278dcf4 870 pi++;
ed35622c 871 if (pi >= max(a->pa, a->pb))
f278dcf4 872 pi++;
873 }
ed35622c 874 print_recurse(s, a->prev, pathindex, pi, priority, assoc, child);
875 } else if (a->prev && index == a->pr &&
876 s->ops[a->po]->display) {
f278dcf4 877 /*
878 * This number was created by a displayed operator in the
879 * transition from this set to its predecessor. Hence we
880 * write an open paren, then recurse into the first
881 * operand, then write the operator, then the second
882 * operand, and finally close the paren.
883 */
884 char *op;
885 int parens, thispri, thisassoc;
886
887 /*
888 * Determine whether we need parentheses.
889 */
ed35622c 890 thispri = s->ops[a->po]->priority;
891 thisassoc = s->ops[a->po]->assoc;
f278dcf4 892 parens = (thispri < priority ||
893 (thispri == priority && (assoc & child)));
894
ed35622c 895 if (parens)
896 putchar('(');
897
898 if (s->ops[a->po]->flags & OPFLAG_UNARYPFX)
899 for (op = s->ops[a->po]->text; *op; op++)
900 putchar(*op);
901
902 print_recurse(s, a->prev, pathindex, a->pa, thispri, thisassoc, 1);
903
904 if (!(s->ops[a->po]->flags & OPFLAG_UNARYPFX))
905 for (op = s->ops[a->po]->text; *op; op++)
906 putchar(*op);
907
908 if (!(s->ops[a->po]->flags & OPFLAG_UNARY))
909 print_recurse(s, a->prev, pathindex, a->pb, thispri, thisassoc, 2);
910
911 if (parens)
912 putchar(')');
f278dcf4 913 } else {
914 /*
915 * This number is either an original, or something formed
916 * by a non-displayed operator (concatenation). Either way,
917 * we display it as is.
918 */
ed35622c 919 printf("%d", ss->numbers[2*index]);
f278dcf4 920 if (ss->numbers[2*index+1] != 1)
ed35622c 921 printf("/%d", ss->numbers[2*index+1]);
922 }
923}
924void print_recurse(struct sets *s, struct set *ss, int pathindex, int index,
925 int priority, int assoc, int child)
926{
927 if (!ss->a.prev || pathindex < ss->a.prev->npaths) {
928 print_recurse_inner(s, ss, &ss->a, pathindex,
929 index, priority, assoc, child);
930 } else {
931 int i;
932 pathindex -= ss->a.prev->npaths;
933 for (i = 0; i < ss->nas; i++) {
934 if (pathindex < ss->as[i].prev->npaths) {
935 print_recurse_inner(s, ss, &ss->as[i], pathindex,
936 index, priority, assoc, child);
937 break;
938 }
939 pathindex -= ss->as[i].prev->npaths;
f278dcf4 940 }
941 }
942}
ed35622c 943void print(int pathindex, struct sets *s, struct output *o)
f278dcf4 944{
ed35622c 945 print_recurse(s, o->set, pathindex, o->index, 0, 0, 0);
f278dcf4 946}
947
ed35622c 948/*
949 * gcc -g -O0 -o numgame numgame.c -I.. ../{malloc,tree234,nullfe}.c -lm
950 */
f278dcf4 951int main(int argc, char **argv)
952{
953 int doing_opts = TRUE;
954 const struct rules *rules = NULL;
955 char *pname = argv[0];
956 int got_target = FALSE, target = 0;
957 int numbers[10], nnumbers = 0;
958 int verbose = FALSE;
959 int pathcounts = FALSE;
ed35622c 960 int multiple = FALSE;
91623748 961 int debug_bfs = FALSE;
f278dcf4 962
963 struct output *o;
964 struct sets *s;
965 int i, start, limit;
966
967 while (--argc) {
968 char *p = *++argv;
969 int c;
970
971 if (doing_opts && *p == '-') {
972 p++;
973
974 if (!strcmp(p, "-")) {
975 doing_opts = FALSE;
976 continue;
91623748 977 } else if (*p == '-') {
978 p++;
979 if (!strcmp(p, "debug-bfs")) {
980 debug_bfs = TRUE;
981 } else {
982 fprintf(stderr, "%s: option '--%s' not recognised\n",
983 pname, p);
984 }
f278dcf4 985 } else while (*p) switch (c = *p++) {
986 case 'C':
987 rules = &rules_countdown;
988 break;
989 case 'B':
990 rules = &rules_3388;
991 break;
992 case 'D':
993 rules = &rules_four4s;
994 break;
ed35622c 995 case 'A':
996 rules = &rules_anythinggoes;
997 break;
f278dcf4 998 case 'v':
999 verbose = TRUE;
1000 break;
1001 case 'p':
1002 pathcounts = TRUE;
1003 break;
ed35622c 1004 case 'm':
1005 multiple = TRUE;
1006 break;
f278dcf4 1007 case 't':
1008 {
1009 char *v;
1010 if (*p) {
1011 v = p;
1012 p = NULL;
1013 } else if (--argc) {
1014 v = *++argv;
1015 } else {
1016 fprintf(stderr, "%s: option '-%c' expects an"
1017 " argument\n", pname, c);
1018 return 1;
1019 }
1020 switch (c) {
1021 case 't':
1022 got_target = TRUE;
1023 target = atoi(v);
1024 break;
1025 }
1026 }
1027 break;
1028 default:
1029 fprintf(stderr, "%s: option '-%c' not"
1030 " recognised\n", pname, c);
1031 return 1;
1032 }
1033 } else {
1034 if (nnumbers >= lenof(numbers)) {
1035 fprintf(stderr, "%s: internal limit of %d numbers exceeded\n",
1036 pname, lenof(numbers));
1037 return 1;
1038 } else {
1039 numbers[nnumbers++] = atoi(p);
1040 }
1041 }
1042 }
1043
1044 if (!rules) {
ed35622c 1045 fprintf(stderr, "%s: no rule set specified; use -C,-B,-D,-A\n", pname);
f278dcf4 1046 return 1;
1047 }
1048
1049 if (!nnumbers) {
1050 fprintf(stderr, "%s: no input numbers specified\n", pname);
1051 return 1;
1052 }
1053
ed35622c 1054 s = do_search(nnumbers, numbers, rules, (got_target ? &target : NULL),
91623748 1055 debug_bfs, multiple);
f278dcf4 1056
1057 if (got_target) {
1058 o = findrelpos234(s->outputtree, &target, outputfindcmp,
1059 REL234_LE, &start);
1060 if (!o)
1061 start = -1;
1062 o = findrelpos234(s->outputtree, &target, outputfindcmp,
1063 REL234_GE, &limit);
1064 if (!o)
1065 limit = -1;
1066 assert(start != -1 || limit != -1);
1067 if (start == -1)
1068 start = limit;
1069 else if (limit == -1)
1070 limit = start;
1071 limit++;
1072 } else {
1073 start = 0;
1074 limit = count234(s->outputtree);
1075 }
1076
1077 for (i = start; i < limit; i++) {
ed35622c 1078 char buf[256];
1079
f278dcf4 1080 o = index234(s->outputtree, i);
1081
ed35622c 1082 sprintf(buf, "%d", o->number);
f278dcf4 1083
1084 if (pathcounts)
ed35622c 1085 sprintf(buf + strlen(buf), " [%d]", o->npaths);
f278dcf4 1086
1087 if (got_target || verbose) {
ed35622c 1088 int j, npaths;
f278dcf4 1089
ed35622c 1090 if (multiple)
1091 npaths = o->npaths;
1092 else
1093 npaths = 1;
1094
1095 for (j = 0; j < npaths; j++) {
1096 printf("%s = ", buf);
1097 print(j, s, o);
1098 putchar('\n');
1099 }
1100 } else {
1101 printf("%s\n", buf);
1102 }
f278dcf4 1103 }
1104
1105 free_sets(s);
1106
1107 return 0;
1108}