latin.c 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. #include <assert.h>
  2. #include <string.h>
  3. #include <stdarg.h>
  4. #include "puzzles.h"
  5. #include "tree234.h"
  6. #include "matching.h"
  7. #ifdef STANDALONE_LATIN_TEST
  8. #define STANDALONE_SOLVER
  9. #endif
  10. #include "latin.h"
  11. /* --------------------------------------------------------
  12. * Solver.
  13. */
  14. static int latin_solver_top(struct latin_solver *solver, int maxdiff,
  15. int diff_simple, int diff_set_0, int diff_set_1,
  16. int diff_forcing, int diff_recursive,
  17. usersolver_t const *usersolvers, validator_t valid,
  18. void *ctx, ctxnew_t ctxnew, ctxfree_t ctxfree);
  19. #ifdef STANDALONE_SOLVER
  20. int solver_show_working, solver_recurse_depth;
  21. #endif
  22. /*
  23. * Function called when we are certain that a particular square has
  24. * a particular number in it. The y-coordinate passed in here is
  25. * transformed.
  26. */
  27. void latin_solver_place(struct latin_solver *solver, int x, int y, int n)
  28. {
  29. int i, o = solver->o;
  30. assert(n <= o);
  31. assert(cube(x,y,n));
  32. /*
  33. * Rule out all other numbers in this square.
  34. */
  35. for (i = 1; i <= o; i++)
  36. if (i != n)
  37. cube(x,y,i) = false;
  38. /*
  39. * Rule out this number in all other positions in the row.
  40. */
  41. for (i = 0; i < o; i++)
  42. if (i != y)
  43. cube(x,i,n) = false;
  44. /*
  45. * Rule out this number in all other positions in the column.
  46. */
  47. for (i = 0; i < o; i++)
  48. if (i != x)
  49. cube(i,y,n) = false;
  50. /*
  51. * Enter the number in the result grid.
  52. */
  53. solver->grid[y*o+x] = n;
  54. /*
  55. * Cross out this number from the list of numbers left to place
  56. * in its row, its column and its block.
  57. */
  58. solver->row[y*o+n-1] = solver->col[x*o+n-1] = true;
  59. }
  60. int latin_solver_elim(struct latin_solver *solver, int start, int step
  61. #ifdef STANDALONE_SOLVER
  62. , const char *fmt, ...
  63. #endif
  64. )
  65. {
  66. int o = solver->o;
  67. #ifdef STANDALONE_SOLVER
  68. char **names = solver->names;
  69. #endif
  70. int fpos, m, i;
  71. /*
  72. * Count the number of set bits within this section of the
  73. * cube.
  74. */
  75. m = 0;
  76. fpos = -1;
  77. for (i = 0; i < o; i++)
  78. if (solver->cube[start+i*step]) {
  79. fpos = start+i*step;
  80. m++;
  81. }
  82. if (m == 1) {
  83. int x, y, n;
  84. assert(fpos >= 0);
  85. n = 1 + fpos % o;
  86. y = fpos / o;
  87. x = y / o;
  88. y %= o;
  89. if (!solver->grid[y*o+x]) {
  90. #ifdef STANDALONE_SOLVER
  91. if (solver_show_working) {
  92. va_list ap;
  93. printf("%*s", solver_recurse_depth*4, "");
  94. va_start(ap, fmt);
  95. vprintf(fmt, ap);
  96. va_end(ap);
  97. printf(":\n%*s placing %s at (%d,%d)\n",
  98. solver_recurse_depth*4, "", names[n-1],
  99. x+1, y+1);
  100. }
  101. #endif
  102. latin_solver_place(solver, x, y, n);
  103. return +1;
  104. }
  105. } else if (m == 0) {
  106. #ifdef STANDALONE_SOLVER
  107. if (solver_show_working) {
  108. va_list ap;
  109. printf("%*s", solver_recurse_depth*4, "");
  110. va_start(ap, fmt);
  111. vprintf(fmt, ap);
  112. va_end(ap);
  113. printf(":\n%*s no possibilities available\n",
  114. solver_recurse_depth*4, "");
  115. }
  116. #endif
  117. return -1;
  118. }
  119. return 0;
  120. }
  121. struct latin_solver_scratch {
  122. unsigned char *grid, *rowidx, *colidx, *set;
  123. int *neighbours, *bfsqueue;
  124. #ifdef STANDALONE_SOLVER
  125. int *bfsprev;
  126. #endif
  127. };
  128. int latin_solver_set(struct latin_solver *solver,
  129. struct latin_solver_scratch *scratch,
  130. int start, int step1, int step2
  131. #ifdef STANDALONE_SOLVER
  132. , const char *fmt, ...
  133. #endif
  134. )
  135. {
  136. int o = solver->o;
  137. #ifdef STANDALONE_SOLVER
  138. char **names = solver->names;
  139. #endif
  140. int i, j, n, count;
  141. unsigned char *grid = scratch->grid;
  142. unsigned char *rowidx = scratch->rowidx;
  143. unsigned char *colidx = scratch->colidx;
  144. unsigned char *set = scratch->set;
  145. /*
  146. * We are passed a o-by-o matrix of booleans. Our first job
  147. * is to winnow it by finding any definite placements - i.e.
  148. * any row with a solitary 1 - and discarding that row and the
  149. * column containing the 1.
  150. */
  151. memset(rowidx, true, o);
  152. memset(colidx, true, o);
  153. for (i = 0; i < o; i++) {
  154. int count = 0, first = -1;
  155. for (j = 0; j < o; j++)
  156. if (solver->cube[start+i*step1+j*step2])
  157. first = j, count++;
  158. if (count == 0) return -1;
  159. if (count == 1)
  160. rowidx[i] = colidx[first] = false;
  161. }
  162. /*
  163. * Convert each of rowidx/colidx from a list of 0s and 1s to a
  164. * list of the indices of the 1s.
  165. */
  166. for (i = j = 0; i < o; i++)
  167. if (rowidx[i])
  168. rowidx[j++] = i;
  169. n = j;
  170. for (i = j = 0; i < o; i++)
  171. if (colidx[i])
  172. colidx[j++] = i;
  173. assert(n == j);
  174. /*
  175. * And create the smaller matrix.
  176. */
  177. for (i = 0; i < n; i++)
  178. for (j = 0; j < n; j++)
  179. grid[i*o+j] = solver->cube[start+rowidx[i]*step1+colidx[j]*step2];
  180. /*
  181. * Having done that, we now have a matrix in which every row
  182. * has at least two 1s in. Now we search to see if we can find
  183. * a rectangle of zeroes (in the set-theoretic sense of
  184. * `rectangle', i.e. a subset of rows crossed with a subset of
  185. * columns) whose width and height add up to n.
  186. */
  187. memset(set, 0, n);
  188. count = 0;
  189. while (1) {
  190. /*
  191. * We have a candidate set. If its size is <=1 or >=n-1
  192. * then we move on immediately.
  193. */
  194. if (count > 1 && count < n-1) {
  195. /*
  196. * The number of rows we need is n-count. See if we can
  197. * find that many rows which each have a zero in all
  198. * the positions listed in `set'.
  199. */
  200. int rows = 0;
  201. for (i = 0; i < n; i++) {
  202. bool ok = true;
  203. for (j = 0; j < n; j++)
  204. if (set[j] && grid[i*o+j]) {
  205. ok = false;
  206. break;
  207. }
  208. if (ok)
  209. rows++;
  210. }
  211. /*
  212. * We expect never to be able to get _more_ than
  213. * n-count suitable rows: this would imply that (for
  214. * example) there are four numbers which between them
  215. * have at most three possible positions, and hence it
  216. * indicates a faulty deduction before this point or
  217. * even a bogus clue.
  218. */
  219. if (rows > n - count) {
  220. #ifdef STANDALONE_SOLVER
  221. if (solver_show_working) {
  222. va_list ap;
  223. printf("%*s", solver_recurse_depth*4,
  224. "");
  225. va_start(ap, fmt);
  226. vprintf(fmt, ap);
  227. va_end(ap);
  228. printf(":\n%*s contradiction reached\n",
  229. solver_recurse_depth*4, "");
  230. }
  231. #endif
  232. return -1;
  233. }
  234. if (rows >= n - count) {
  235. bool progress = false;
  236. /*
  237. * We've got one! Now, for each row which _doesn't_
  238. * satisfy the criterion, eliminate all its set
  239. * bits in the positions _not_ listed in `set'.
  240. * Return +1 (meaning progress has been made) if we
  241. * successfully eliminated anything at all.
  242. *
  243. * This involves referring back through
  244. * rowidx/colidx in order to work out which actual
  245. * positions in the cube to meddle with.
  246. */
  247. for (i = 0; i < n; i++) {
  248. bool ok = true;
  249. for (j = 0; j < n; j++)
  250. if (set[j] && grid[i*o+j]) {
  251. ok = false;
  252. break;
  253. }
  254. if (!ok) {
  255. for (j = 0; j < n; j++)
  256. if (!set[j] && grid[i*o+j]) {
  257. int fpos = (start+rowidx[i]*step1+
  258. colidx[j]*step2);
  259. #ifdef STANDALONE_SOLVER
  260. if (solver_show_working) {
  261. int px, py, pn;
  262. if (!progress) {
  263. va_list ap;
  264. printf("%*s", solver_recurse_depth*4,
  265. "");
  266. va_start(ap, fmt);
  267. vprintf(fmt, ap);
  268. va_end(ap);
  269. printf(":\n");
  270. }
  271. pn = 1 + fpos % o;
  272. py = fpos / o;
  273. px = py / o;
  274. py %= o;
  275. printf("%*s ruling out %s at (%d,%d)\n",
  276. solver_recurse_depth*4, "",
  277. names[pn-1], px+1, py+1);
  278. }
  279. #endif
  280. progress = true;
  281. solver->cube[fpos] = false;
  282. }
  283. }
  284. }
  285. if (progress) {
  286. return +1;
  287. }
  288. }
  289. }
  290. /*
  291. * Binary increment: change the rightmost 0 to a 1, and
  292. * change all 1s to the right of it to 0s.
  293. */
  294. i = n;
  295. while (i > 0 && set[i-1])
  296. set[--i] = 0, count--;
  297. if (i > 0)
  298. set[--i] = 1, count++;
  299. else
  300. break; /* done */
  301. }
  302. return 0;
  303. }
  304. /*
  305. * Look for forcing chains. A forcing chain is a path of
  306. * pairwise-exclusive squares (i.e. each pair of adjacent squares
  307. * in the path are in the same row, column or block) with the
  308. * following properties:
  309. *
  310. * (a) Each square on the path has precisely two possible numbers.
  311. *
  312. * (b) Each pair of squares which are adjacent on the path share
  313. * at least one possible number in common.
  314. *
  315. * (c) Each square in the middle of the path shares _both_ of its
  316. * numbers with at least one of its neighbours (not the same
  317. * one with both neighbours).
  318. *
  319. * These together imply that at least one of the possible number
  320. * choices at one end of the path forces _all_ the rest of the
  321. * numbers along the path. In order to make real use of this, we
  322. * need further properties:
  323. *
  324. * (c) Ruling out some number N from the square at one end
  325. * of the path forces the square at the other end to
  326. * take number N.
  327. *
  328. * (d) The two end squares are both in line with some third
  329. * square.
  330. *
  331. * (e) That third square currently has N as a possibility.
  332. *
  333. * If we can find all of that lot, we can deduce that at least one
  334. * of the two ends of the forcing chain has number N, and that
  335. * therefore the mutually adjacent third square does not.
  336. *
  337. * To find forcing chains, we're going to start a bfs at each
  338. * suitable square, once for each of its two possible numbers.
  339. */
  340. int latin_solver_forcing(struct latin_solver *solver,
  341. struct latin_solver_scratch *scratch)
  342. {
  343. int o = solver->o;
  344. #ifdef STANDALONE_SOLVER
  345. char **names = solver->names;
  346. #endif
  347. int *bfsqueue = scratch->bfsqueue;
  348. #ifdef STANDALONE_SOLVER
  349. int *bfsprev = scratch->bfsprev;
  350. #endif
  351. unsigned char *number = scratch->grid;
  352. int *neighbours = scratch->neighbours;
  353. int x, y;
  354. for (y = 0; y < o; y++)
  355. for (x = 0; x < o; x++) {
  356. int count, t, n;
  357. /*
  358. * If this square doesn't have exactly two candidate
  359. * numbers, don't try it.
  360. *
  361. * In this loop we also sum the candidate numbers,
  362. * which is a nasty hack to allow us to quickly find
  363. * `the other one' (since we will shortly know there
  364. * are exactly two).
  365. */
  366. for (count = t = 0, n = 1; n <= o; n++)
  367. if (cube(x, y, n))
  368. count++, t += n;
  369. if (count != 2)
  370. continue;
  371. /*
  372. * Now attempt a bfs for each candidate.
  373. */
  374. for (n = 1; n <= o; n++)
  375. if (cube(x, y, n)) {
  376. int orign, currn, head, tail;
  377. /*
  378. * Begin a bfs.
  379. */
  380. orign = n;
  381. memset(number, o+1, o*o);
  382. head = tail = 0;
  383. bfsqueue[tail++] = y*o+x;
  384. #ifdef STANDALONE_SOLVER
  385. bfsprev[y*o+x] = -1;
  386. #endif
  387. number[y*o+x] = t - n;
  388. while (head < tail) {
  389. int xx, yy, nneighbours, xt, yt, i;
  390. xx = bfsqueue[head++];
  391. yy = xx / o;
  392. xx %= o;
  393. currn = number[yy*o+xx];
  394. /*
  395. * Find neighbours of yy,xx.
  396. */
  397. nneighbours = 0;
  398. for (yt = 0; yt < o; yt++)
  399. neighbours[nneighbours++] = yt*o+xx;
  400. for (xt = 0; xt < o; xt++)
  401. neighbours[nneighbours++] = yy*o+xt;
  402. /*
  403. * Try visiting each of those neighbours.
  404. */
  405. for (i = 0; i < nneighbours; i++) {
  406. int cc, tt, nn;
  407. xt = neighbours[i] % o;
  408. yt = neighbours[i] / o;
  409. /*
  410. * We need this square to not be
  411. * already visited, and to include
  412. * currn as a possible number.
  413. */
  414. if (number[yt*o+xt] <= o)
  415. continue;
  416. if (!cube(xt, yt, currn))
  417. continue;
  418. /*
  419. * Don't visit _this_ square a second
  420. * time!
  421. */
  422. if (xt == xx && yt == yy)
  423. continue;
  424. /*
  425. * To continue with the bfs, we need
  426. * this square to have exactly two
  427. * possible numbers.
  428. */
  429. for (cc = tt = 0, nn = 1; nn <= o; nn++)
  430. if (cube(xt, yt, nn))
  431. cc++, tt += nn;
  432. if (cc == 2) {
  433. bfsqueue[tail++] = yt*o+xt;
  434. #ifdef STANDALONE_SOLVER
  435. bfsprev[yt*o+xt] = yy*o+xx;
  436. #endif
  437. number[yt*o+xt] = tt - currn;
  438. }
  439. /*
  440. * One other possibility is that this
  441. * might be the square in which we can
  442. * make a real deduction: if it's
  443. * adjacent to x,y, and currn is equal
  444. * to the original number we ruled out.
  445. */
  446. if (currn == orign &&
  447. (xt == x || yt == y)) {
  448. #ifdef STANDALONE_SOLVER
  449. if (solver_show_working) {
  450. const char *sep = "";
  451. int xl, yl;
  452. printf("%*sforcing chain, %s at ends of ",
  453. solver_recurse_depth*4, "",
  454. names[orign-1]);
  455. xl = xx;
  456. yl = yy;
  457. while (1) {
  458. printf("%s(%d,%d)", sep, xl+1,
  459. yl+1);
  460. xl = bfsprev[yl*o+xl];
  461. if (xl < 0)
  462. break;
  463. yl = xl / o;
  464. xl %= o;
  465. sep = "-";
  466. }
  467. printf("\n%*s ruling out %s at (%d,%d)\n",
  468. solver_recurse_depth*4, "",
  469. names[orign-1],
  470. xt+1, yt+1);
  471. }
  472. #endif
  473. cube(xt, yt, orign) = false;
  474. return 1;
  475. }
  476. }
  477. }
  478. }
  479. }
  480. return 0;
  481. }
  482. struct latin_solver_scratch *latin_solver_new_scratch(struct latin_solver *solver)
  483. {
  484. struct latin_solver_scratch *scratch = snew(struct latin_solver_scratch);
  485. int o = solver->o;
  486. scratch->grid = snewn(o*o, unsigned char);
  487. scratch->rowidx = snewn(o, unsigned char);
  488. scratch->colidx = snewn(o, unsigned char);
  489. scratch->set = snewn(o, unsigned char);
  490. scratch->neighbours = snewn(3*o, int);
  491. scratch->bfsqueue = snewn(o*o, int);
  492. #ifdef STANDALONE_SOLVER
  493. scratch->bfsprev = snewn(o*o, int);
  494. #endif
  495. return scratch;
  496. }
  497. void latin_solver_free_scratch(struct latin_solver_scratch *scratch)
  498. {
  499. #ifdef STANDALONE_SOLVER
  500. sfree(scratch->bfsprev);
  501. #endif
  502. sfree(scratch->bfsqueue);
  503. sfree(scratch->neighbours);
  504. sfree(scratch->set);
  505. sfree(scratch->colidx);
  506. sfree(scratch->rowidx);
  507. sfree(scratch->grid);
  508. sfree(scratch);
  509. }
  510. bool latin_solver_alloc(struct latin_solver *solver, digit *grid, int o)
  511. {
  512. int x, y;
  513. solver->o = o;
  514. solver->cube = snewn(o*o*o, unsigned char);
  515. solver->grid = grid; /* write straight back to the input */
  516. memset(solver->cube, 1, o*o*o);
  517. solver->row = snewn(o*o, unsigned char);
  518. solver->col = snewn(o*o, unsigned char);
  519. memset(solver->row, 0, o*o);
  520. memset(solver->col, 0, o*o);
  521. #ifdef STANDALONE_SOLVER
  522. solver->names = NULL;
  523. #endif
  524. for (x = 0; x < o; x++) {
  525. for (y = 0; y < o; y++) {
  526. int n = grid[y*o+x];
  527. if (n) {
  528. if (cube(x, y, n))
  529. latin_solver_place(solver, x, y, n);
  530. else
  531. return false; /* puzzle is already inconsistent */
  532. }
  533. }
  534. }
  535. return true;
  536. }
  537. void latin_solver_free(struct latin_solver *solver)
  538. {
  539. sfree(solver->cube);
  540. sfree(solver->row);
  541. sfree(solver->col);
  542. }
  543. int latin_solver_diff_simple(struct latin_solver *solver)
  544. {
  545. int x, y, n, ret, o = solver->o;
  546. #ifdef STANDALONE_SOLVER
  547. char **names = solver->names;
  548. #endif
  549. /*
  550. * Row-wise positional elimination.
  551. */
  552. for (y = 0; y < o; y++)
  553. for (n = 1; n <= o; n++)
  554. if (!solver->row[y*o+n-1]) {
  555. ret = latin_solver_elim(solver, cubepos(0,y,n), o*o
  556. #ifdef STANDALONE_SOLVER
  557. , "positional elimination,"
  558. " %s in row %d", names[n-1],
  559. y+1
  560. #endif
  561. );
  562. if (ret != 0) return ret;
  563. }
  564. /*
  565. * Column-wise positional elimination.
  566. */
  567. for (x = 0; x < o; x++)
  568. for (n = 1; n <= o; n++)
  569. if (!solver->col[x*o+n-1]) {
  570. ret = latin_solver_elim(solver, cubepos(x,0,n), o
  571. #ifdef STANDALONE_SOLVER
  572. , "positional elimination,"
  573. " %s in column %d", names[n-1], x+1
  574. #endif
  575. );
  576. if (ret != 0) return ret;
  577. }
  578. /*
  579. * Numeric elimination.
  580. */
  581. for (x = 0; x < o; x++)
  582. for (y = 0; y < o; y++)
  583. if (!solver->grid[y*o+x]) {
  584. ret = latin_solver_elim(solver, cubepos(x,y,1), 1
  585. #ifdef STANDALONE_SOLVER
  586. , "numeric elimination at (%d,%d)",
  587. x+1, y+1
  588. #endif
  589. );
  590. if (ret != 0) return ret;
  591. }
  592. return 0;
  593. }
  594. int latin_solver_diff_set(struct latin_solver *solver,
  595. struct latin_solver_scratch *scratch,
  596. bool extreme)
  597. {
  598. int x, y, n, ret, o = solver->o;
  599. #ifdef STANDALONE_SOLVER
  600. char **names = solver->names;
  601. #endif
  602. if (!extreme) {
  603. /*
  604. * Row-wise set elimination.
  605. */
  606. for (y = 0; y < o; y++) {
  607. ret = latin_solver_set(solver, scratch, cubepos(0,y,1), o*o, 1
  608. #ifdef STANDALONE_SOLVER
  609. , "set elimination, row %d", y+1
  610. #endif
  611. );
  612. if (ret != 0) return ret;
  613. }
  614. /*
  615. * Column-wise set elimination.
  616. */
  617. for (x = 0; x < o; x++) {
  618. ret = latin_solver_set(solver, scratch, cubepos(x,0,1), o, 1
  619. #ifdef STANDALONE_SOLVER
  620. , "set elimination, column %d", x+1
  621. #endif
  622. );
  623. if (ret != 0) return ret;
  624. }
  625. } else {
  626. /*
  627. * Row-vs-column set elimination on a single number
  628. * (much tricker for a human to do!)
  629. */
  630. for (n = 1; n <= o; n++) {
  631. ret = latin_solver_set(solver, scratch, cubepos(0,0,n), o*o, o
  632. #ifdef STANDALONE_SOLVER
  633. , "positional set elimination on %s",
  634. names[n-1]
  635. #endif
  636. );
  637. if (ret != 0) return ret;
  638. }
  639. }
  640. return 0;
  641. }
  642. /*
  643. * Returns:
  644. * 0 for 'didn't do anything' implying it was already solved.
  645. * -1 for 'impossible' (no solution)
  646. * 1 for 'single solution'
  647. * >1 for 'multiple solutions' (you don't get to know how many, and
  648. * the first such solution found will be set.
  649. *
  650. * and this function may well assert if given an impossible board.
  651. */
  652. static int latin_solver_recurse
  653. (struct latin_solver *solver, int diff_simple, int diff_set_0,
  654. int diff_set_1, int diff_forcing, int diff_recursive,
  655. usersolver_t const *usersolvers, validator_t valid, void *ctx,
  656. ctxnew_t ctxnew, ctxfree_t ctxfree)
  657. {
  658. int best, bestcount;
  659. int o = solver->o, x, y, n;
  660. #ifdef STANDALONE_SOLVER
  661. char **names = solver->names;
  662. #endif
  663. best = -1;
  664. bestcount = o+1;
  665. for (y = 0; y < o; y++)
  666. for (x = 0; x < o; x++)
  667. if (!solver->grid[y*o+x]) {
  668. int count;
  669. /*
  670. * An unfilled square. Count the number of
  671. * possible digits in it.
  672. */
  673. count = 0;
  674. for (n = 1; n <= o; n++)
  675. if (cube(x,y,n))
  676. count++;
  677. /*
  678. * We should have found any impossibilities
  679. * already, so this can safely be an assert.
  680. */
  681. assert(count > 1);
  682. if (count < bestcount) {
  683. bestcount = count;
  684. best = y*o+x;
  685. }
  686. }
  687. if (best == -1)
  688. /* we were complete already. */
  689. return 0;
  690. else {
  691. int i, j;
  692. digit *list, *ingrid, *outgrid;
  693. int diff = diff_impossible; /* no solution found yet */
  694. /*
  695. * Attempt recursion.
  696. */
  697. y = best / o;
  698. x = best % o;
  699. list = snewn(o, digit);
  700. ingrid = snewn(o*o, digit);
  701. outgrid = snewn(o*o, digit);
  702. memcpy(ingrid, solver->grid, o*o);
  703. /* Make a list of the possible digits. */
  704. for (j = 0, n = 1; n <= o; n++)
  705. if (cube(x,y,n))
  706. list[j++] = n;
  707. #ifdef STANDALONE_SOLVER
  708. if (solver_show_working) {
  709. const char *sep = "";
  710. printf("%*srecursing on (%d,%d) [",
  711. solver_recurse_depth*4, "", x+1, y+1);
  712. for (i = 0; i < j; i++) {
  713. printf("%s%s", sep, names[list[i]-1]);
  714. sep = " or ";
  715. }
  716. printf("]\n");
  717. }
  718. #endif
  719. /*
  720. * And step along the list, recursing back into the
  721. * main solver at every stage.
  722. */
  723. for (i = 0; i < j; i++) {
  724. int ret;
  725. void *newctx;
  726. struct latin_solver subsolver;
  727. memcpy(outgrid, ingrid, o*o);
  728. outgrid[y*o+x] = list[i];
  729. #ifdef STANDALONE_SOLVER
  730. if (solver_show_working)
  731. printf("%*sguessing %s at (%d,%d)\n",
  732. solver_recurse_depth*4, "", names[list[i]-1], x+1, y+1);
  733. solver_recurse_depth++;
  734. #endif
  735. if (ctxnew) {
  736. newctx = ctxnew(ctx);
  737. } else {
  738. newctx = ctx;
  739. }
  740. #ifdef STANDALONE_SOLVER
  741. subsolver.names = solver->names;
  742. #endif
  743. if (latin_solver_alloc(&subsolver, outgrid, o))
  744. ret = latin_solver_top(&subsolver, diff_recursive,
  745. diff_simple, diff_set_0, diff_set_1,
  746. diff_forcing, diff_recursive,
  747. usersolvers, valid, newctx,
  748. ctxnew, ctxfree);
  749. else
  750. ret = diff_impossible;
  751. latin_solver_free(&subsolver);
  752. if (ctxnew)
  753. ctxfree(newctx);
  754. #ifdef STANDALONE_SOLVER
  755. solver_recurse_depth--;
  756. if (solver_show_working) {
  757. printf("%*sretracting %s at (%d,%d)\n",
  758. solver_recurse_depth*4, "", names[list[i]-1], x+1, y+1);
  759. }
  760. #endif
  761. /* we recurse as deep as we can, so we should never find
  762. * find ourselves giving up on a puzzle without declaring it
  763. * impossible. */
  764. assert(ret != diff_unfinished);
  765. /*
  766. * If we have our first solution, copy it into the
  767. * grid we will return.
  768. */
  769. if (diff == diff_impossible && ret != diff_impossible)
  770. memcpy(solver->grid, outgrid, o*o);
  771. if (ret == diff_ambiguous)
  772. diff = diff_ambiguous;
  773. else if (ret == diff_impossible)
  774. /* do not change our return value */;
  775. else {
  776. /* the recursion turned up exactly one solution */
  777. if (diff == diff_impossible)
  778. diff = diff_recursive;
  779. else
  780. diff = diff_ambiguous;
  781. }
  782. /*
  783. * As soon as we've found more than one solution,
  784. * give up immediately.
  785. */
  786. if (diff == diff_ambiguous)
  787. break;
  788. }
  789. sfree(outgrid);
  790. sfree(ingrid);
  791. sfree(list);
  792. if (diff == diff_impossible)
  793. return -1;
  794. else if (diff == diff_ambiguous)
  795. return 2;
  796. else {
  797. assert(diff == diff_recursive);
  798. return 1;
  799. }
  800. }
  801. }
  802. static int latin_solver_top(struct latin_solver *solver, int maxdiff,
  803. int diff_simple, int diff_set_0, int diff_set_1,
  804. int diff_forcing, int diff_recursive,
  805. usersolver_t const *usersolvers, validator_t valid,
  806. void *ctx, ctxnew_t ctxnew, ctxfree_t ctxfree)
  807. {
  808. struct latin_solver_scratch *scratch = latin_solver_new_scratch(solver);
  809. int ret, diff = diff_simple;
  810. assert(maxdiff <= diff_recursive);
  811. /*
  812. * Now loop over the grid repeatedly trying all permitted modes
  813. * of reasoning. The loop terminates if we complete an
  814. * iteration without making any progress; we then return
  815. * failure or success depending on whether the grid is full or
  816. * not.
  817. */
  818. while (1) {
  819. int i;
  820. cont:
  821. latin_solver_debug(solver->cube, solver->o);
  822. for (i = 0; i <= maxdiff; i++) {
  823. if (usersolvers[i])
  824. ret = usersolvers[i](solver, ctx);
  825. else
  826. ret = 0;
  827. if (ret == 0 && i == diff_simple)
  828. ret = latin_solver_diff_simple(solver);
  829. if (ret == 0 && i == diff_set_0)
  830. ret = latin_solver_diff_set(solver, scratch, false);
  831. if (ret == 0 && i == diff_set_1)
  832. ret = latin_solver_diff_set(solver, scratch, true);
  833. if (ret == 0 && i == diff_forcing)
  834. ret = latin_solver_forcing(solver, scratch);
  835. if (ret < 0) {
  836. diff = diff_impossible;
  837. goto got_result;
  838. } else if (ret > 0) {
  839. diff = max(diff, i);
  840. goto cont;
  841. }
  842. }
  843. /*
  844. * If we reach here, we have made no deductions in this
  845. * iteration, so the algorithm terminates.
  846. */
  847. break;
  848. }
  849. /*
  850. * Last chance: if we haven't fully solved the puzzle yet, try
  851. * recursing based on guesses for a particular square. We pick
  852. * one of the most constrained empty squares we can find, which
  853. * has the effect of pruning the search tree as much as
  854. * possible.
  855. */
  856. if (maxdiff == diff_recursive) {
  857. int nsol = latin_solver_recurse(solver,
  858. diff_simple, diff_set_0, diff_set_1,
  859. diff_forcing, diff_recursive,
  860. usersolvers, valid, ctx,
  861. ctxnew, ctxfree);
  862. if (nsol < 0) diff = diff_impossible;
  863. else if (nsol == 1) diff = diff_recursive;
  864. else if (nsol > 1) diff = diff_ambiguous;
  865. /* if nsol == 0 then we were complete anyway
  866. * (and thus don't need to change diff) */
  867. } else {
  868. /*
  869. * We're forbidden to use recursion, so we just see whether
  870. * our grid is fully solved, and return diff_unfinished
  871. * otherwise.
  872. */
  873. int x, y, o = solver->o;
  874. for (y = 0; y < o; y++)
  875. for (x = 0; x < o; x++)
  876. if (!solver->grid[y*o+x])
  877. diff = diff_unfinished;
  878. }
  879. got_result:
  880. #ifdef STANDALONE_SOLVER
  881. if (solver_show_working) {
  882. if (diff != diff_impossible && diff != diff_unfinished &&
  883. diff != diff_ambiguous) {
  884. int x, y;
  885. printf("%*sone solution found:\n", solver_recurse_depth*4, "");
  886. for (y = 0; y < solver->o; y++) {
  887. printf("%*s", solver_recurse_depth*4+1, "");
  888. for (x = 0; x < solver->o; x++) {
  889. int val = solver->grid[y*solver->o+x];
  890. assert(val);
  891. printf(" %s", solver->names[val-1]);
  892. }
  893. printf("\n");
  894. }
  895. } else {
  896. printf("%*s%s found\n",
  897. solver_recurse_depth*4, "",
  898. diff == diff_impossible ? "no solution (impossible)" :
  899. diff == diff_unfinished ? "no solution (unfinished)" :
  900. "multiple solutions");
  901. }
  902. }
  903. #endif
  904. if (diff != diff_impossible && diff != diff_unfinished &&
  905. diff != diff_ambiguous && valid && !valid(solver, ctx)) {
  906. #ifdef STANDALONE_SOLVER
  907. if (solver_show_working) {
  908. printf("%*ssolution failed final validation!\n",
  909. solver_recurse_depth*4, "");
  910. }
  911. #endif
  912. diff = diff_impossible;
  913. }
  914. latin_solver_free_scratch(scratch);
  915. return diff;
  916. }
  917. int latin_solver_main(struct latin_solver *solver, int maxdiff,
  918. int diff_simple, int diff_set_0, int diff_set_1,
  919. int diff_forcing, int diff_recursive,
  920. usersolver_t const *usersolvers, validator_t valid,
  921. void *ctx, ctxnew_t ctxnew, ctxfree_t ctxfree)
  922. {
  923. int diff;
  924. #ifdef STANDALONE_SOLVER
  925. int o = solver->o;
  926. char *text = NULL, **names = NULL;
  927. #endif
  928. #ifdef STANDALONE_SOLVER
  929. if (!solver->names) {
  930. char *p;
  931. int i;
  932. text = snewn(40 * o, char);
  933. p = text;
  934. solver->names = snewn(o, char *);
  935. for (i = 0; i < o; i++) {
  936. solver->names[i] = p;
  937. p += 1 + sprintf(p, "%d", i+1);
  938. }
  939. }
  940. #endif
  941. diff = latin_solver_top(solver, maxdiff,
  942. diff_simple, diff_set_0, diff_set_1,
  943. diff_forcing, diff_recursive,
  944. usersolvers, valid, ctx, ctxnew, ctxfree);
  945. #ifdef STANDALONE_SOLVER
  946. sfree(names);
  947. sfree(text);
  948. #endif
  949. return diff;
  950. }
  951. int latin_solver(digit *grid, int o, int maxdiff,
  952. int diff_simple, int diff_set_0, int diff_set_1,
  953. int diff_forcing, int diff_recursive,
  954. usersolver_t const *usersolvers, validator_t valid,
  955. void *ctx, ctxnew_t ctxnew, ctxfree_t ctxfree)
  956. {
  957. struct latin_solver solver;
  958. int diff;
  959. if (latin_solver_alloc(&solver, grid, o))
  960. diff = latin_solver_main(&solver, maxdiff,
  961. diff_simple, diff_set_0, diff_set_1,
  962. diff_forcing, diff_recursive,
  963. usersolvers, valid, ctx, ctxnew, ctxfree);
  964. else
  965. diff = diff_impossible;
  966. latin_solver_free(&solver);
  967. return diff;
  968. }
  969. void latin_solver_debug(unsigned char *cube, int o)
  970. {
  971. #ifdef STANDALONE_SOLVER
  972. if (solver_show_working > 1) {
  973. struct latin_solver ls, *solver = &ls;
  974. char *dbg;
  975. int x, y, i, c = 0;
  976. ls.cube = cube; ls.o = o; /* for cube() to work */
  977. dbg = snewn(3*o*o*o, char);
  978. for (y = 0; y < o; y++) {
  979. for (x = 0; x < o; x++) {
  980. for (i = 1; i <= o; i++) {
  981. if (cube(x,y,i))
  982. dbg[c++] = i + '0';
  983. else
  984. dbg[c++] = '.';
  985. }
  986. dbg[c++] = ' ';
  987. }
  988. dbg[c++] = '\n';
  989. }
  990. dbg[c++] = '\n';
  991. dbg[c++] = '\0';
  992. printf("%s", dbg);
  993. sfree(dbg);
  994. }
  995. #endif
  996. }
  997. void latin_debug(digit *sq, int o)
  998. {
  999. #ifdef STANDALONE_SOLVER
  1000. if (solver_show_working) {
  1001. int x, y;
  1002. for (y = 0; y < o; y++) {
  1003. for (x = 0; x < o; x++) {
  1004. printf("%2d ", sq[y*o+x]);
  1005. }
  1006. printf("\n");
  1007. }
  1008. printf("\n");
  1009. }
  1010. #endif
  1011. }
  1012. /* --------------------------------------------------------
  1013. * Generation.
  1014. */
  1015. digit *latin_generate(int o, random_state *rs)
  1016. {
  1017. digit *sq;
  1018. int *adjdata, *adjsizes, *matching;
  1019. int **adjlists;
  1020. void *scratch;
  1021. int i, j, k;
  1022. digit *row;
  1023. /*
  1024. * To efficiently generate a latin square in such a way that
  1025. * all possible squares are possible outputs from the function,
  1026. * we make use of a theorem which states that any r x n latin
  1027. * rectangle, with r < n, can be extended into an (r+1) x n
  1028. * latin rectangle. In other words, we can reliably generate a
  1029. * latin square row by row, by at every stage writing down any
  1030. * row at all which doesn't conflict with previous rows, and
  1031. * the theorem guarantees that we will never have to backtrack.
  1032. *
  1033. * To find a viable row at each stage, we can make use of the
  1034. * support functions in matching.c.
  1035. */
  1036. sq = snewn(o*o, digit);
  1037. /*
  1038. * matching.c will take care of randomising the generation of each
  1039. * row of the square, but in case this entire method of generation
  1040. * introduces a really subtle top-to-bottom directional bias,
  1041. * we'll also generate the rows themselves in random order.
  1042. */
  1043. row = snewn(o, digit);
  1044. for (i = 0; i < o; i++)
  1045. row[i] = i;
  1046. shuffle(row, i, sizeof(*row), rs);
  1047. /*
  1048. * Set up the infrastructure for the matching subroutine.
  1049. */
  1050. scratch = smalloc(matching_scratch_size(o, o));
  1051. adjdata = snewn(o*o, int);
  1052. adjlists = snewn(o, int *);
  1053. adjsizes = snewn(o, int);
  1054. matching = snewn(o, int);
  1055. /*
  1056. * Now generate each row of the latin square.
  1057. */
  1058. for (i = 0; i < o; i++) {
  1059. /*
  1060. * Make adjacency lists for a bipartite graph joining each
  1061. * column to all the numbers not yet placed in that column.
  1062. */
  1063. for (j = 0; j < o; j++) {
  1064. int *p, *adj = adjdata + j*o;
  1065. for (k = 0; k < o; k++)
  1066. adj[k] = 1;
  1067. for (k = 0; k < i; k++)
  1068. adj[sq[row[k]*o + j] - 1] = 0;
  1069. adjlists[j] = p = adj;
  1070. for (k = 0; k < o; k++)
  1071. if (adj[k])
  1072. *p++ = k;
  1073. adjsizes[j] = p - adjlists[j];
  1074. }
  1075. /*
  1076. * Run the matching algorithm.
  1077. */
  1078. j = matching_with_scratch(scratch, o, o, adjlists, adjsizes,
  1079. rs, matching, NULL);
  1080. assert(j == o); /* by the above theorem, this must have succeeded */
  1081. /*
  1082. * And use the output to set up the new row of the latin
  1083. * square.
  1084. */
  1085. for (j = 0; j < o; j++)
  1086. sq[row[i]*o + j] = matching[j] + 1;
  1087. }
  1088. /*
  1089. * Done. Free our internal workspaces...
  1090. */
  1091. sfree(matching);
  1092. sfree(adjlists);
  1093. sfree(adjsizes);
  1094. sfree(adjdata);
  1095. sfree(scratch);
  1096. sfree(row);
  1097. /*
  1098. * ... and return our completed latin square.
  1099. */
  1100. return sq;
  1101. }
  1102. digit *latin_generate_rect(int w, int h, random_state *rs)
  1103. {
  1104. int o = max(w, h), x, y;
  1105. digit *latin, *latin_rect;
  1106. latin = latin_generate(o, rs);
  1107. latin_rect = snewn(w*h, digit);
  1108. for (x = 0; x < w; x++) {
  1109. for (y = 0; y < h; y++) {
  1110. latin_rect[y*w + x] = latin[y*o + x];
  1111. }
  1112. }
  1113. sfree(latin);
  1114. return latin_rect;
  1115. }
  1116. /* --------------------------------------------------------
  1117. * Checking.
  1118. */
  1119. typedef struct lcparams {
  1120. digit elt;
  1121. int count;
  1122. } lcparams;
  1123. static int latin_check_cmp(void *v1, void *v2)
  1124. {
  1125. lcparams *lc1 = (lcparams *)v1;
  1126. lcparams *lc2 = (lcparams *)v2;
  1127. if (lc1->elt < lc2->elt) return -1;
  1128. if (lc1->elt > lc2->elt) return 1;
  1129. return 0;
  1130. }
  1131. #define ELT(sq,x,y) (sq[((y)*order)+(x)])
  1132. /* returns true if sq is not a latin square. */
  1133. bool latin_check(digit *sq, int order)
  1134. {
  1135. tree234 *dict = newtree234(latin_check_cmp);
  1136. int c, r;
  1137. bool ret = false;
  1138. lcparams *lcp, lc, *aret;
  1139. /* Use a tree234 as a simple hash table, go through the square
  1140. * adding elements as we go or incrementing their counts. */
  1141. for (c = 0; c < order; c++) {
  1142. for (r = 0; r < order; r++) {
  1143. lc.elt = ELT(sq, c, r); lc.count = 0;
  1144. lcp = find234(dict, &lc, NULL);
  1145. if (!lcp) {
  1146. lcp = snew(lcparams);
  1147. lcp->elt = ELT(sq, c, r);
  1148. lcp->count = 1;
  1149. aret = add234(dict, lcp);
  1150. assert(aret == lcp);
  1151. } else {
  1152. lcp->count++;
  1153. }
  1154. }
  1155. }
  1156. /* There should be precisely 'order' letters in the alphabet,
  1157. * each occurring 'order' times (making the OxO tree) */
  1158. if (count234(dict) != order) ret = true;
  1159. else {
  1160. for (c = 0; (lcp = index234(dict, c)) != NULL; c++) {
  1161. if (lcp->count != order) ret = true;
  1162. }
  1163. }
  1164. for (c = 0; (lcp = index234(dict, c)) != NULL; c++)
  1165. sfree(lcp);
  1166. freetree234(dict);
  1167. return ret;
  1168. }
  1169. /* vim: set shiftwidth=4 tabstop=8: */