@altnovatrail/picture-kit 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +1 -1
  2. package/lib/index.d.ts +45 -1
  3. package/lib/index.js +34 -3
  4. package/lib/kinds/balance.js +2 -3
  5. package/lib/kinds/calendar.d.ts +5 -1
  6. package/lib/kinds/calendar.js +33 -11
  7. package/lib/kinds/chart.js +2 -4
  8. package/lib/kinds/clock.d.ts +5 -0
  9. package/lib/kinds/clock.js +45 -4
  10. package/lib/kinds/coins.js +3 -2
  11. package/lib/kinds/column.js +2 -3
  12. package/lib/kinds/commands.d.ts +8 -6
  13. package/lib/kinds/commands.js +57 -15
  14. package/lib/kinds/containers.js +2 -1
  15. package/lib/kinds/countfig.d.ts +2 -0
  16. package/lib/kinds/countfig.js +6 -1
  17. package/lib/kinds/cubes.d.ts +29 -5
  18. package/lib/kinds/cubes.js +82 -34
  19. package/lib/kinds/die.d.ts +8 -0
  20. package/lib/kinds/die.js +75 -14
  21. package/lib/kinds/domino.js +3 -3
  22. package/lib/kinds/dotgrid.d.ts +3 -0
  23. package/lib/kinds/dotgrid.js +6 -4
  24. package/lib/kinds/figure.js +5 -4
  25. package/lib/kinds/fold-parts.d.ts +0 -2
  26. package/lib/kinds/fold-parts.js +0 -4
  27. package/lib/kinds/fold.d.ts +20 -1
  28. package/lib/kinds/fold.js +15 -6
  29. package/lib/kinds/fraction.js +3 -2
  30. package/lib/kinds/gauges.js +2 -1
  31. package/lib/kinds/gears.d.ts +21 -2
  32. package/lib/kinds/gears.js +113 -62
  33. package/lib/kinds/grid.d.ts +5 -0
  34. package/lib/kinds/grid.js +30 -2
  35. package/lib/kinds/groups.d.ts +3 -1
  36. package/lib/kinds/groups.js +142 -28
  37. package/lib/kinds/lanes.js +3 -2
  38. package/lib/kinds/layers.d.ts +6 -0
  39. package/lib/kinds/layers.js +23 -4
  40. package/lib/kinds/line.d.ts +4 -0
  41. package/lib/kinds/line.js +117 -32
  42. package/lib/kinds/matchsticks.d.ts +4 -0
  43. package/lib/kinds/matchsticks.js +5 -3
  44. package/lib/kinds/net.js +4 -3
  45. package/lib/kinds/overlay.d.ts +23 -1
  46. package/lib/kinds/overlay.js +7 -3
  47. package/lib/kinds/pieces.js +3 -2
  48. package/lib/kinds/plane-parts.d.ts +0 -2
  49. package/lib/kinds/plane-parts.js +0 -6
  50. package/lib/kinds/plane.js +6 -6
  51. package/lib/kinds/ropes.js +1 -3
  52. package/lib/kinds/shapes.js +5 -7
  53. package/lib/kinds/solids.js +3 -2
  54. package/lib/kinds/tangram.js +2 -4
  55. package/lib/kinds/target.js +4 -6
  56. package/lib/kinds/tiles.js +5 -4
  57. package/lib/kinds/venn.js +3 -5
  58. package/lib/noto.js +1 -0
  59. package/lib/objects.js +2 -1
  60. package/lib/read.d.ts +2 -2
  61. package/lib/read.js +3 -3
  62. package/lib/solve/balance.d.ts +11 -0
  63. package/lib/solve/balance.js +116 -1
  64. package/lib/solve/calendar.d.ts +46 -0
  65. package/lib/solve/calendar.js +206 -0
  66. package/lib/solve/choice-scenes.d.ts +20 -0
  67. package/lib/solve/choice-scenes.js +51 -0
  68. package/lib/solve/clock.d.ts +54 -0
  69. package/lib/solve/clock.js +240 -0
  70. package/lib/solve/coins.d.ts +71 -0
  71. package/lib/solve/coins.js +222 -0
  72. package/lib/solve/commands.d.ts +36 -0
  73. package/lib/solve/commands.js +210 -0
  74. package/lib/solve/countfig.d.ts +41 -0
  75. package/lib/solve/countfig.js +199 -0
  76. package/lib/solve/cubes.d.ts +49 -0
  77. package/lib/solve/cubes.js +255 -0
  78. package/lib/solve/die.d.ts +39 -0
  79. package/lib/solve/die.js +93 -0
  80. package/lib/solve/domino.d.ts +57 -0
  81. package/lib/solve/domino.js +263 -0
  82. package/lib/solve/enumerate.d.ts +75 -0
  83. package/lib/solve/enumerate.js +323 -0
  84. package/lib/solve/figure.d.ts +26 -0
  85. package/lib/solve/figure.js +88 -0
  86. package/lib/solve/fold.d.ts +22 -0
  87. package/lib/solve/fold.js +68 -0
  88. package/lib/solve/gaps.d.ts +65 -0
  89. package/lib/solve/gaps.js +292 -0
  90. package/lib/solve/gears.d.ts +33 -0
  91. package/lib/solve/gears.js +130 -0
  92. package/lib/solve/grid.d.ts +35 -0
  93. package/lib/solve/grid.js +194 -0
  94. package/lib/solve/groups.d.ts +93 -0
  95. package/lib/solve/groups.js +346 -0
  96. package/lib/solve/index.d.ts +60 -0
  97. package/lib/solve/index.js +194 -0
  98. package/lib/solve/layers.d.ts +30 -0
  99. package/lib/solve/layers.js +72 -0
  100. package/lib/solve/magic.d.ts +32 -0
  101. package/lib/solve/magic.js +216 -0
  102. package/lib/solve/matchsticks.d.ts +37 -0
  103. package/lib/solve/matchsticks.js +214 -0
  104. package/lib/solve/order.d.ts +94 -0
  105. package/lib/solve/order.js +419 -0
  106. package/lib/solve/overlay.d.ts +22 -0
  107. package/lib/solve/overlay.js +56 -0
  108. package/lib/solve/parity.d.ts +22 -0
  109. package/lib/solve/parity.js +27 -0
  110. package/lib/solve/pattern.d.ts +62 -0
  111. package/lib/solve/pattern.js +533 -0
  112. package/lib/solve/pieces.d.ts +57 -0
  113. package/lib/solve/pieces.js +309 -0
  114. package/lib/solve/pigeonhole.d.ts +38 -0
  115. package/lib/solve/pigeonhole.js +95 -0
  116. package/lib/solve/proof.d.ts +115 -0
  117. package/lib/solve/proof.js +105 -0
  118. package/lib/solve/pyramid.d.ts +28 -0
  119. package/lib/solve/pyramid.js +161 -0
  120. package/lib/solve/question.d.ts +25 -0
  121. package/lib/solve/question.js +75 -0
  122. package/lib/solve/shapes.d.ts +30 -0
  123. package/lib/solve/shapes.js +182 -0
  124. package/lib/solve/target.d.ts +40 -0
  125. package/lib/solve/target.js +190 -0
  126. package/lib/style.d.ts +1 -1
  127. package/lib/style.js +1 -1
  128. package/lib/words.d.ts +15 -0
  129. package/lib/words.js +39 -0
  130. package/package.json +1 -1
@@ -0,0 +1,309 @@
1
+ import { colors } from "../style.js";
2
+ import { choicesOf } from "./choice-scenes.js";
3
+ import { letters, noScene, solved, unsolved, } from "./proof.js";
4
+ import { askOf, flagOf, sceneless } from "./question.js";
5
+ const members = {
6
+ "fills-gap": ["flip"],
7
+ "how-many-cover": ["flip"],
8
+ "which-pair": ["flip"],
9
+ "odd-one-out": ["flip", "anyColor"],
10
+ };
11
+ /** The largest board how-many-cover lays copies on, in squares. */
12
+ const mostCovered = 36;
13
+ const quartersOf = {
14
+ full: [0, 1, 2, 3],
15
+ nw: [0, 3],
16
+ ne: [0, 1],
17
+ sw: [2, 3],
18
+ se: [1, 2],
19
+ };
20
+ function shapeOf(cells) {
21
+ return cells.flatMap((s) => quartersOf[s[2] ?? "full"].map((q) => [s[0], s[1], q]));
22
+ }
23
+ function boardShape(board) {
24
+ if (board.cells)
25
+ return shapeOf(board.cells);
26
+ const out = [];
27
+ for (let r = 0; r < board.rows; r++)
28
+ for (let c = 0; c < board.cols; c++)
29
+ out.push([r, c]);
30
+ return shapeOf(out);
31
+ }
32
+ const order = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
33
+ const keyOf = (q) => `${q[0]},${q[1]},${q[2]}`;
34
+ /** normal moves a shape so that its top row and left column are 0, and sorts its quarters. */
35
+ function normal(shape) {
36
+ const r0 = Math.min(...shape.map((q) => q[0]));
37
+ const c0 = Math.min(...shape.map((q) => q[1]));
38
+ return shape.map((q) => [q[0] - r0, q[1] - c0, q[2]]).sort(order);
39
+ }
40
+ const turned = (shape) => shape.map((q) => [q[1], -q[0], (q[2] + 1) % 4]);
41
+ const mirrored = (shape) => shape.map((q) => [q[0], -q[1], q[2] % 2 === 1 ? 4 - q[2] : q[2]]);
42
+ /** poses lists the different ways a shape lies, each normal: turned, and flipped too if flip. */
43
+ function poses(shape, flip) {
44
+ const out = new Map();
45
+ for (const start of flip ? [shape, mirrored(shape)] : [shape]) {
46
+ let s = start;
47
+ for (let k = 0; k < 4; k++) {
48
+ const n = normal(s);
49
+ out.set(n.map(keyOf).join(" "), n);
50
+ s = turned(s);
51
+ }
52
+ }
53
+ return [...out.values()];
54
+ }
55
+ /** sameShape tells whether a shape lies as another, turned, and flipped too if flip. */
56
+ function sameShape(a, b, flip) {
57
+ if (a.length !== b.length)
58
+ return false;
59
+ const target = normal(b).map(keyOf).join(" ");
60
+ return poses(a, flip).some((p) => p.map(keyOf).join(" ") === target);
61
+ }
62
+ /**
63
+ * cover tells whether copies of the pieces, each of its poses, lay on the board with no gap and
64
+ * no overlap: the first quarter still bare, in the order of rows, columns and sides, is always a
65
+ * piece's own first quarter, so every way of laying is tried once. counts says how many of each
66
+ * piece to lay, or undefined for as many as it takes.
67
+ */
68
+ function cover(board, pieces, counts) {
69
+ const bare = new Set(board.map(keyOf));
70
+ const sorted = [...board].sort(order);
71
+ const left = counts ? [...counts] : undefined;
72
+ const lay = () => {
73
+ const first = sorted.find((q) => bare.has(keyOf(q)));
74
+ if (!first)
75
+ return !left || left.every((k) => k === 0);
76
+ for (let i = 0; i < pieces.length; i++) {
77
+ if (left && left[i] === 0)
78
+ continue;
79
+ for (const pose of pieces[i]) {
80
+ const a = pose[0];
81
+ if (a[2] !== first[2])
82
+ continue;
83
+ const at = pose.map((q) => keyOf([q[0] - a[0] + first[0], q[1] - a[1] + first[1], q[2]]));
84
+ if (!at.every((k) => bare.has(k)))
85
+ continue;
86
+ for (const k of at)
87
+ bare.delete(k);
88
+ if (left)
89
+ left[i]--;
90
+ const done = lay();
91
+ if (left)
92
+ left[i]++;
93
+ for (const k of at)
94
+ bare.add(k);
95
+ if (done)
96
+ return true;
97
+ }
98
+ }
99
+ return false;
100
+ };
101
+ return lay();
102
+ }
103
+ const isPieces = (scene) => scene.kind === "pieces";
104
+ const isTangram = (scene) => scene.kind === "tangram";
105
+ /** The only piece of a tangram whose mirror image no turn gives. */
106
+ const handed = "parallelogram";
107
+ function fitsGap(gap, piece, flip) {
108
+ if (gap.piece !== piece.piece)
109
+ return false;
110
+ return flip || gap.piece !== handed || (gap.flip === true) === (piece.flip === true);
111
+ }
112
+ /** holeOf is the shape of the empty places of a floor of tiles in a grid. */
113
+ function holeOf(scene) {
114
+ const cols = scene.columns ?? 3;
115
+ return shapeOf(scene.tiles.flatMap((t, i) => (t.empty ? [[Math.floor(i / cols), i % cols]] : [])));
116
+ }
117
+ function checkLabels(labels, list_, ask, problems) {
118
+ const bare = labels.indexOf(undefined);
119
+ if (bare >= 0)
120
+ problems.push(`${list_}[${bare}].label: ${ask} names a piece by its label`);
121
+ else if (new Set(labels).size < labels.length)
122
+ problems.push(`${list_}: ${ask} names a piece by its label, and two pieces share one`);
123
+ }
124
+ /** onePiece refuses a picture option that is not one piece with no board. */
125
+ function onePiece(o, path, problems) {
126
+ if (o.pieces.length !== 1)
127
+ problems.push(`${path}.pieces: an option is one piece`);
128
+ if (o.board !== undefined)
129
+ problems.push(`${path}.board: an option is a piece with no board`);
130
+ }
131
+ function checkTiles(scene, offered, problems) {
132
+ if (scene.shape !== "square" || scene.layout !== "grid")
133
+ problems.push("scene: fills-gap reads a floor of square tiles in a grid");
134
+ const plain = ["fill", "empty"];
135
+ scene.tiles.forEach((t, i) => {
136
+ for (const m of Object.keys(t))
137
+ if (!plain.includes(m))
138
+ problems.push(`tiles[${i}].${m}: fills-gap reads a floor of plain tiles and its gap`);
139
+ });
140
+ if (!scene.tiles.some((t) => t.empty))
141
+ problems.push("tiles: fills-gap needs the gap, empty places of the floor");
142
+ choicesOf(offered, "fills-gap", "pieces", onePiece, problems);
143
+ }
144
+ function checkFor(ask, scene, offered, q) {
145
+ const problems = [];
146
+ if (ask === "fills-gap") {
147
+ if (isPieces(scene)) {
148
+ problems.push("scene.kind: fills-gap reads a tangram figure or a floor of tiles");
149
+ return problems;
150
+ }
151
+ if (!isTangram(scene)) {
152
+ checkTiles(scene, offered, problems);
153
+ return problems;
154
+ }
155
+ if ((offered?.choices ?? []).length > 0)
156
+ problems.push("choices: fills-gap on a tangram figure reads its pieces apart, labelled");
157
+ const gaps = (scene.pieces ?? []).filter((p) => p.missing).length;
158
+ if (gaps !== 1)
159
+ problems.push(`pieces: fills-gap needs exactly one missing piece, not ${gaps}`);
160
+ const apart = scene.apart ?? [];
161
+ if (apart.length < 2)
162
+ problems.push("apart: fills-gap needs two pieces apart or more");
163
+ else
164
+ checkLabels(apart.map((p) => p.label), "apart", ask, problems);
165
+ return problems;
166
+ }
167
+ if (!isPieces(scene)) {
168
+ problems.push(`scene.kind: ${ask} reads a scene of pieces`);
169
+ return problems;
170
+ }
171
+ const pieces = scene.pieces;
172
+ const labels = pieces.map((p) => p.label);
173
+ if (ask === "how-many-cover") {
174
+ if (pieces.length !== 1)
175
+ problems.push("pieces: how-many-cover counts copies of one piece");
176
+ if (!scene.board)
177
+ problems.push("board: how-many-cover needs the board to cover");
178
+ else if (boardShape(scene.board).length > 4 * mostCovered)
179
+ problems.push(`board: how-many-cover lays copies on a board of at most ${mostCovered} squares`);
180
+ }
181
+ if (ask === "which-pair") {
182
+ if (pieces.length < 2)
183
+ problems.push("pieces: which-pair needs two pieces or more");
184
+ if (!scene.board)
185
+ problems.push("board: which-pair needs the board the two pieces cover");
186
+ checkLabels(labels, "pieces", ask, problems);
187
+ }
188
+ if (ask === "odd-one-out") {
189
+ if (pieces.length < 3)
190
+ problems.push("pieces: odd-one-out needs three pieces or more");
191
+ checkLabels(labels, "pieces", ask, problems);
192
+ const first = pieces[0].color;
193
+ const other = pieces.findIndex((p) => p.color !== first);
194
+ if (other >= 0 && q.anyColor !== true)
195
+ problems.push(`pieces[${other}].color: is ${colors[pieces[other].color].word}, not ${colors[first].word}; a piece of another colour stands out, unless the question says anyColor`);
196
+ }
197
+ return problems;
198
+ }
199
+ function check(question, givens, scene, offered) {
200
+ const problems = [];
201
+ const read = askOf(question, members, problems);
202
+ if (!read)
203
+ return problems;
204
+ if (givens !== undefined)
205
+ problems.push(`givens: ${read.ask} takes none`);
206
+ flagOf(read.q.flip, "question.flip", problems);
207
+ flagOf(read.q.anyColor, "question.anyColor", problems);
208
+ if (scene)
209
+ problems.push(...checkFor(read.ask, scene, offered, read.q));
210
+ else
211
+ sceneless(read.ask, "a scene of pieces, a tangram or a floor of tiles", problems);
212
+ return problems;
213
+ }
214
+ /** fitting proves the one option that fits the gap; none, or two or more, have no answer. */
215
+ function fitting(fit, reads, value) {
216
+ if (fit.length === 1)
217
+ return solved(value === "text" ? { text: fit[0] } : { letter: fit[0] }, reads);
218
+ if (fit.length === 0)
219
+ return unsolved("no option fills the gap exactly", reads);
220
+ return unsolved(`${fit.join(" and ")} all fill the gap exactly`, reads);
221
+ }
222
+ function solve(scene, question, _givens, offered) {
223
+ if (!scene)
224
+ return noScene;
225
+ const flip = question.flip === true;
226
+ if (isTangram(scene)) {
227
+ const figure = scene.pieces ?? [];
228
+ const apart = scene.apart ?? [];
229
+ const gap = figure.find((p) => p.missing);
230
+ const reads = [...figure.map((_, i) => `pieces[${i}]`), ...apart.map((_, j) => `apart[${j}]`)];
231
+ const fit = apart.filter((p) => fitsGap(gap, p, flip)).map((p) => p.label);
232
+ return fitting(fit, reads, "text");
233
+ }
234
+ if (!isPieces(scene)) {
235
+ const hole = holeOf(scene);
236
+ const reads = scene.tiles.map((_, i) => `tiles[${i}]`);
237
+ const fit = (offered?.choices ?? []).flatMap((o, i) => sameShape(shapeOf(o.pieces[0].cells), hole, flip) ? [letters[i]] : []);
238
+ return fitting(fit, reads, "letter");
239
+ }
240
+ const shapes = scene.pieces.map((p) => shapeOf(p.cells));
241
+ const reads = [...scene.pieces.map((_, i) => `pieces[${i}]`), ...(scene.board ? ["board"] : [])];
242
+ const labels = scene.pieces.map((p) => p.label);
243
+ switch (question.ask) {
244
+ case "how-many-cover": {
245
+ const board = boardShape(scene.board);
246
+ const piece = shapes[0];
247
+ if (board.length % piece.length !== 0 || !cover(board, [poses(piece, flip)]))
248
+ return unsolved("copies of the piece cannot cover the board with no gap", reads);
249
+ return solved({ number: board.length / piece.length }, reads);
250
+ }
251
+ case "which-pair": {
252
+ const board = boardShape(scene.board);
253
+ const pairs = [];
254
+ shapes.forEach((a, i) => {
255
+ shapes.forEach((b, j) => {
256
+ if (j <= i || a.length + b.length !== board.length)
257
+ return;
258
+ if (cover(board, [poses(a, flip), poses(b, flip)], [1, 1]))
259
+ pairs.push(`${labels[i]} and ${labels[j]}`);
260
+ });
261
+ });
262
+ if (pairs.length === 1)
263
+ return solved({ text: pairs[0] }, reads);
264
+ if (pairs.length === 0)
265
+ return unsolved("no two pieces cover the board with no gap", reads);
266
+ return unsolved(`${pairs.join("; ")} each cover the board`, reads);
267
+ }
268
+ default: {
269
+ const kinds = [];
270
+ shapes.forEach((s, i) => {
271
+ const same = kinds.find((k) => sameShape(shapes[k[0]], s, flip));
272
+ if (same)
273
+ same.push(i);
274
+ else
275
+ kinds.push([i]);
276
+ });
277
+ const odd = kinds.length === 2 ? kinds.find((k) => k.length === 1) : undefined;
278
+ if (odd)
279
+ return solved({ text: labels[odd[0]] }, reads);
280
+ if (kinds.length === 1)
281
+ return unsolved("every piece has the same shape", reads);
282
+ const each = kinds.map((k) => k.map((i) => labels[i]).join(" ")).join("; ");
283
+ return unsolved(`the pieces have ${kinds.length} shapes (${each}); no one piece alone differs`, reads);
284
+ }
285
+ }
286
+ }
287
+ /**
288
+ * The facts of a scene of pieces are its pieces and its board; of a tangram, the pieces of its
289
+ * figure and those apart; of a floor of tiles, its tiles and its centre.
290
+ */
291
+ function facts(scene) {
292
+ if (isPieces(scene))
293
+ return [...scene.pieces.map((_, i) => `pieces[${i}]`), ...(scene.board ? ["board"] : [])];
294
+ if (isTangram(scene))
295
+ return [
296
+ ...(scene.pieces ?? []).map((_, i) => `pieces[${i}]`),
297
+ ...(scene.apart ?? []).map((_, j) => `apart[${j}]`),
298
+ ];
299
+ return [...scene.tiles.map((_, i) => `tiles[${i}]`), ...(scene.centre ? ["centre"] : [])];
300
+ }
301
+ /** piecesSolver fits pieces of squared paper and of a tangram: the questions of PiecesQuestion. */
302
+ export const piecesSolver = {
303
+ name: "pieces",
304
+ kinds: ["pieces", "tangram", "tiles"],
305
+ questions: Object.keys(members),
306
+ check,
307
+ facts,
308
+ solve,
309
+ };
@@ -0,0 +1,38 @@
1
+ import type { GroupsScene } from "../kinds/groups.ts";
2
+ import { type Thing } from "../things.ts";
3
+ import { type Solver } from "./proof.ts";
4
+ /**
5
+ * The givens of what one is sure to get: k, how many alike are wanted, and
6
+ * of, the thing wanted, for sure-k-of; of, the things wanted one of each,
7
+ * for sure-one-of-each, every thing of the container when it is left out.
8
+ */
9
+ export type PigeonholeGivens = {
10
+ k?: number;
11
+ of?: Thing | Thing[];
12
+ };
13
+ /**
14
+ * The questions of what one is sure to get, taking things without looking
15
+ * from one container — the one group of a scene of groups, drawn or the
16
+ * hidden scene of a statement in words —, each thing of the group (a ball of
17
+ * a colour, say) with its count. Each answer is the fewest things to take,
18
+ * a number: the unluckiest handful, every thing that does not help taken
19
+ * first, and one more.
20
+ *
21
+ * - `sure-k-of`: to be sure of givens.k alike, of any thing, or of the
22
+ * thing givens.of.
23
+ * - `sure-one-of-each`: to be sure of one of each thing, or of each of the
24
+ * things givens.of.
25
+ *
26
+ * A "sure" that cannot happen — two green balls from a jar with one — is
27
+ * never sure, however many are taken: its answer is the text "never", a
28
+ * definite answer, which an option {"text": "never"} names and "it cannot be
29
+ * told" does not.
30
+ */
31
+ export type PigeonholeQuestion = {
32
+ ask: "sure-k-of" | "sure-one-of-each";
33
+ };
34
+ /**
35
+ * pigeonholeSolver finds what one is sure to get from a container: the
36
+ * questions of PigeonholeQuestion.
37
+ */
38
+ export declare const pigeonholeSolver: Solver<GroupsScene, PigeonholeQuestion, PigeonholeGivens>;
@@ -0,0 +1,95 @@
1
+ import { int, isObj, list, only } from "../read.js";
2
+ import { checkThing, sameThing, wordOf } from "../things.js";
3
+ import { noScene, solved } from "./proof.js";
4
+ import { askOf, sceneless } from "./question.js";
5
+ const members = { "sure-k-of": [], "sure-one-of-each": [] };
6
+ /** The answer of a "sure" that cannot happen. */
7
+ const never = { text: "never" };
8
+ function pilesOf(scene) {
9
+ return scene.groups[0].items.map((item) => ({ thing: item.thing, count: item.count }));
10
+ }
11
+ function check(question, givens, scene) {
12
+ const problems = [];
13
+ const read = askOf(question, members, problems);
14
+ if (!read)
15
+ return problems;
16
+ const { ask } = read;
17
+ if (givens !== undefined && !isObj(givens)) {
18
+ problems.push("givens: must be an object");
19
+ return problems;
20
+ }
21
+ const g = givens ?? {};
22
+ only(g, ask === "sure-k-of" ? ["k", "of"] : ["of"], "givens", problems, `the givens of ${ask}`);
23
+ const before = problems.length;
24
+ if (!scene)
25
+ sceneless(ask, "the container, a scene of groups drawn or hidden", problems);
26
+ else {
27
+ if (scene.groups.length !== 1)
28
+ problems.push("groups: the things are taken from one container, one group");
29
+ else
30
+ scene.groups[0].items.forEach((item, j) => {
31
+ const first = scene.groups[0].items.findIndex((o) => sameThing(o.thing, item.thing));
32
+ if (first !== j)
33
+ problems.push(`groups[0].items[${j}]: ${wordOf(item.thing, 2)} stand in two items`);
34
+ });
35
+ }
36
+ const piles = scene && problems.length === before ? pilesOf(scene) : undefined;
37
+ const inside = (t, path) => {
38
+ const before = problems.length;
39
+ checkThing(t, path, problems);
40
+ if (problems.length === before && piles && !piles.some((p) => sameThing(p.thing, t)))
41
+ problems.push(`${path}: the container holds no ${wordOf(t, 2)}`);
42
+ };
43
+ if (ask === "sure-k-of") {
44
+ int(g.k, "givens.k", problems, 1, 24);
45
+ if (g.of !== undefined)
46
+ inside(g.of, "givens.of");
47
+ }
48
+ else if (g.of !== undefined)
49
+ list(g.of, "givens.of", problems, 1, 4).forEach((t, i) => {
50
+ inside(t, `givens.of[${i}]`);
51
+ });
52
+ if (piles && piles.length < 2 && g.of === undefined)
53
+ problems.push("groups[0]: holds one thing only, so every handful is alike");
54
+ return problems;
55
+ }
56
+ function solve(scene, question, givens) {
57
+ if (!scene)
58
+ return noScene;
59
+ const piles = pilesOf(scene);
60
+ const reads = piles.map((_, j) => `groups[0].items[${j}]`);
61
+ const total = piles.reduce((s, p) => s + p.count, 0);
62
+ const isOf = (p, of) => sameThing(p.thing, of);
63
+ if (question.ask === "sure-k-of") {
64
+ const k = givens.k;
65
+ const of = givens.of;
66
+ if (of !== undefined) {
67
+ const wanted = piles.find((p) => isOf(p, of));
68
+ if (wanted.count < k)
69
+ return solved(never, reads);
70
+ return solved({ number: total - wanted.count + k }, reads);
71
+ }
72
+ if (!piles.some((p) => p.count >= k))
73
+ return solved(never, reads);
74
+ return solved({ number: piles.reduce((s, p) => s + Math.min(p.count, k - 1), 0) + 1 }, reads);
75
+ }
76
+ const of = givens?.of ?? piles.map((p) => p.thing);
77
+ const fewest = Math.min(...of.map((t) => piles.find((p) => isOf(p, t)).count));
78
+ return solved({ number: total - fewest + 1 }, reads);
79
+ }
80
+ /** The facts of the container are its items, each a thing and its count. */
81
+ function facts(scene) {
82
+ return scene.groups.flatMap((g, i) => g.items.map((_, j) => `groups[${i}].items[${j}]`));
83
+ }
84
+ /**
85
+ * pigeonholeSolver finds what one is sure to get from a container: the
86
+ * questions of PigeonholeQuestion.
87
+ */
88
+ export const pigeonholeSolver = {
89
+ name: "pigeonhole",
90
+ kinds: ["groups"],
91
+ questions: Object.keys(members),
92
+ check,
93
+ facts,
94
+ solve,
95
+ };
@@ -0,0 +1,115 @@
1
+ import { type Problems } from "../read.ts";
2
+ import { type Thing } from "../things.ts";
3
+ /**
4
+ * Value is an answer the way a task's option names it: a number; a thing of
5
+ * the scene; a text — a holder's label, two labels in the order of the scene
6
+ * joined by "and", "A and B", or a word a question's type names, such as
7
+ * "clockwise" or "never"; a letter, of a picture option or of a scene of
8
+ * choices; or yes and no, as a truth.
9
+ */
10
+ export type Value = {
11
+ number: number;
12
+ } | {
13
+ thing: Thing;
14
+ } | {
15
+ text: string;
16
+ } | {
17
+ letter: string;
18
+ } | {
19
+ truth: boolean;
20
+ };
21
+ /** Option is one option of a task: a value, or "it cannot be told", undecided. */
22
+ export type Option = Value | {
23
+ undecided: true;
24
+ };
25
+ /**
26
+ * Offered is what a task offers beside its scene, as the gate gives it to a
27
+ * solver: options, the task's options in their order; and choices, the
28
+ * scenes of its picture options in the order of their letters. A picture
29
+ * option is an option {letter}, lettered by its place among the task's
30
+ * letter options — the first is A and shows choices[0], the next B and
31
+ * shows choices[1] —, as the writer of tasks draws them in one picture of
32
+ * choices. A question that answers among the options reads them here — the
33
+ * totals offered, the tiles or the programs drawn —, never a copy of them in
34
+ * the question or the givens, and answers a picture option by the letter of
35
+ * its scene. Both lists are empty for a task that offers nothing of the kind.
36
+ */
37
+ export type Offered = {
38
+ readonly options: readonly Option[];
39
+ readonly choices: readonly unknown[];
40
+ };
41
+ /** The letters of picture options and of the options of a scene of choices, A first. */
42
+ export declare const letters = "ABCDEF";
43
+ /** nothing is what a task offers a solver that was given no Offered. */
44
+ export declare const nothing: Offered;
45
+ /**
46
+ * Proof is what a solver gives for a question about a scene. Proved, it
47
+ * holds the one answer the scene and the statement allow; unproved, the
48
+ * candidates it could not tell apart — none when the question has no answer
49
+ * at all — and why. Either way reads names, by its path in the scene, every
50
+ * member the solver read, `groups[1].items[0]` say: a fact of the scene that
51
+ * no read covers is a fact the task does not need, and a picture that shows
52
+ * one distracts or lies, so the gate refuses it.
53
+ */
54
+ export type Proof = {
55
+ proved: true;
56
+ answer: Value;
57
+ reads: string[];
58
+ } | {
59
+ proved: false;
60
+ candidates: Value[];
61
+ why: string;
62
+ reads: string[];
63
+ };
64
+ /**
65
+ * Solver is a topic's solver. It reads scenes of its kinds — none for a
66
+ * solver of the statement alone — and answers its questions, each a JSON
67
+ * object whose ask names one of questions. check lists what is wrong with a
68
+ * question, the givens and what the task offers, each problem with its path
69
+ * (`question.of: …`, `givens.weights[0]: …`, `choices[1]: …`); it runs
70
+ * once the scene, the options and the choices have passed their own checks,
71
+ * so that it can refuse a question about what the scene does not hold. A
72
+ * task with no scene reaches it too, and it refuses a question that reads a
73
+ * scene: the scene undefined means the task has none. facts are the paths of
74
+ * the members of a scene that carry what the picture shows, which the reads
75
+ * of a proof must cover. solve runs only on what check passed, with the same
76
+ * offered, and never throws; offered left out is nothing.
77
+ */
78
+ export interface Solver<S = unknown, Q = unknown, G = unknown> {
79
+ readonly name: string;
80
+ readonly kinds: readonly string[];
81
+ readonly questions: readonly string[];
82
+ check(question: unknown, givens: unknown, scene: S | undefined, offered?: Offered): string[];
83
+ facts(scene: S): string[];
84
+ solve(scene: S | undefined, question: Q, givens: G, offered?: Offered): Proof;
85
+ }
86
+ export declare function solved(answer: Value, reads: string[]): Proof;
87
+ export declare function unsolved(why: string, reads: string[], candidates?: Value[]): Proof;
88
+ /** The proof of a solver that reads a scene, given none. */
89
+ export declare const noScene: Proof;
90
+ /** sameValue tells whether two values are the same answer. */
91
+ export declare function sameValue(a: Value, b: Value): boolean;
92
+ /**
93
+ * matches tells whether an option names what a proof proved: a value
94
+ * matches the proved answer, and "it cannot be told" matches a proof that
95
+ * is not proved and has at least two candidates — a question with no answer
96
+ * at all matches no option. It reads the option alone, never its place, so
97
+ * an option matches whatever the order of the options.
98
+ */
99
+ export declare function matches(option: Option, proof: Proof): boolean;
100
+ /** say words a value for a problem. */
101
+ export declare function say(value: Value): string;
102
+ /**
103
+ * provesKey lists what keeps the options from proving the key: exactly one
104
+ * option matches the proof, and it is options[key]. matches reads an option
105
+ * alone, so the key holds whatever order the options are shown in.
106
+ */
107
+ export declare function provesKey(proof: Proof, options: readonly Option[], key: number): string[];
108
+ /**
109
+ * unread lists the facts of a scene that no read covers. A read covers the
110
+ * member at its path and every member inside it: `groups[1]` covers
111
+ * `groups[1].items[0]`.
112
+ */
113
+ export declare function unread(facts: readonly string[], reads: readonly string[]): string[];
114
+ /** checkOption records what is wrong with an option at a path. */
115
+ export declare function checkOption(value: unknown, path: string, problems: Problems): void;
@@ -0,0 +1,105 @@
1
+ import { isObj, only, text } from "../read.js";
2
+ import { checkThing, sameThing, wordOf } from "../things.js";
3
+ /** The letters of picture options and of the options of a scene of choices, A first. */
4
+ export const letters = "ABCDEF";
5
+ /** nothing is what a task offers a solver that was given no Offered. */
6
+ export const nothing = { options: [], choices: [] };
7
+ export function solved(answer, reads) {
8
+ return { proved: true, answer, reads };
9
+ }
10
+ export function unsolved(why, reads, candidates = []) {
11
+ return { proved: false, candidates, why, reads };
12
+ }
13
+ /** The proof of a solver that reads a scene, given none. */
14
+ export const noScene = unsolved("the solver reads a scene, and there is none", []);
15
+ /** sameValue tells whether two values are the same answer. */
16
+ export function sameValue(a, b) {
17
+ if ("number" in a)
18
+ return "number" in b && a.number === b.number;
19
+ if ("thing" in a)
20
+ return "thing" in b && sameThing(a.thing, b.thing);
21
+ if ("text" in a)
22
+ return "text" in b && a.text === b.text;
23
+ if ("letter" in a)
24
+ return "letter" in b && a.letter === b.letter;
25
+ return "truth" in b && a.truth === b.truth;
26
+ }
27
+ /**
28
+ * matches tells whether an option names what a proof proved: a value
29
+ * matches the proved answer, and "it cannot be told" matches a proof that
30
+ * is not proved and has at least two candidates — a question with no answer
31
+ * at all matches no option. It reads the option alone, never its place, so
32
+ * an option matches whatever the order of the options.
33
+ */
34
+ export function matches(option, proof) {
35
+ if ("undecided" in option)
36
+ return !proof.proved && proof.candidates.length >= 2;
37
+ return proof.proved && sameValue(option, proof.answer);
38
+ }
39
+ /** say words a value for a problem. */
40
+ export function say(value) {
41
+ if ("number" in value)
42
+ return String(value.number);
43
+ if ("thing" in value)
44
+ return wordOf(value.thing);
45
+ if ("text" in value)
46
+ return `"${value.text}"`;
47
+ if ("letter" in value)
48
+ return `the letter ${value.letter}`;
49
+ return value.truth ? "yes" : "no";
50
+ }
51
+ function sayProof(proof) {
52
+ if (proof.proved)
53
+ return `the answer is ${say(proof.answer)}`;
54
+ const many = proof.candidates.length >= 2;
55
+ return `the solver proves no answer, ${proof.why}${many ? ", so it cannot be told" : ""}`;
56
+ }
57
+ /**
58
+ * provesKey lists what keeps the options from proving the key: exactly one
59
+ * option matches the proof, and it is options[key]. matches reads an option
60
+ * alone, so the key holds whatever order the options are shown in.
61
+ */
62
+ export function provesKey(proof, options, key) {
63
+ const hits = options.flatMap((o, i) => (matches(o, proof) ? [i] : []));
64
+ if (hits.length === 0)
65
+ return [`options: none matches; ${sayProof(proof)}`];
66
+ if (hits.length > 1)
67
+ return [
68
+ `options: ${hits.map((i) => `options[${i}]`).join(", ")} all match; ${sayProof(proof)}`,
69
+ ];
70
+ if (hits[0] !== key)
71
+ return [`key: options[${hits[0]}] matches, not options[${key}]`];
72
+ return [];
73
+ }
74
+ /**
75
+ * unread lists the facts of a scene that no read covers. A read covers the
76
+ * member at its path and every member inside it: `groups[1]` covers
77
+ * `groups[1].items[0]`.
78
+ */
79
+ export function unread(facts, reads) {
80
+ return facts.filter((f) => !reads.some((r) => f === r || f.startsWith(`${r}.`) || f.startsWith(`${r}[`)));
81
+ }
82
+ const shapes = ["number", "thing", "text", "letter", "truth", "undecided"];
83
+ /** checkOption records what is wrong with an option at a path. */
84
+ export function checkOption(value, path, problems) {
85
+ const shape = isObj(value) ? shapes.filter((s) => value[s] !== undefined) : [];
86
+ if (!isObj(value) || shape.length !== 1) {
87
+ problems.push(`${path}: must be one of {"number"}, {"thing"}, {"text"}, {"letter"}, {"truth"}, {"undecided": true}`);
88
+ return;
89
+ }
90
+ const s = shape[0];
91
+ only(value, [s], path, problems, "an option");
92
+ const v = value[s];
93
+ if (s === "number" && (typeof v !== "number" || !Number.isFinite(v)))
94
+ problems.push(`${path}.number: must be a number`);
95
+ if (s === "thing")
96
+ checkThing(v, `${path}.thing`, problems);
97
+ if (s === "text")
98
+ text(v, `${path}.text`, problems, 40);
99
+ if (s === "letter" && (typeof v !== "string" || !/^[A-Z]$/.test(v)))
100
+ problems.push(`${path}.letter: must be a capital letter, as "B"`);
101
+ if (s === "truth" && typeof v !== "boolean")
102
+ problems.push(`${path}.truth: must be true or false`);
103
+ if (s === "undecided" && v !== true)
104
+ problems.push(`${path}.undecided: must be true`);
105
+ }