numgame.c 34 KB

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