@johnmorrisdotca/jirai 0.2.1 → 0.4.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.
package/src/generate.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { activeCell, activeCells } from "./shape.ts";
2
- import { deduce } from "./deduce.ts";
3
- import { flood } from "./flood.ts";
4
- import { GENERATION_ATTEMPTS, MARKS, STATUSES } from "./jirai.constants.ts";
1
+ import { activeCells } from "./shape.ts";
2
+ import { GENERATION_ATTEMPTS } from "./jirai.constants.ts";
5
3
  import { neighbours, neighboursOf, validCell, validSettings } from "./grid.ts";
4
+ import { repair } from "./repair.ts";
6
5
  import { seededRandom, shuffled } from "./random.ts";
7
- import type { Board, GenerationOptions, Settings, VisibleGame } from "./jirai.types.ts";
6
+ import { Solver } from "./solve.ts";
7
+ import type { Board, GenerationOptions, Settings } from "./jirai.types.ts";
8
8
 
9
9
  /** A bounded generator must say it failed, never quietly return a guessing board. */
10
10
  export class GenerationError extends Error {
@@ -13,45 +13,72 @@ export class GenerationError extends Error {
13
13
 
14
14
  /** Verify a board from one opening, using only clues that have been uncovered. */
15
15
  export function isSolvable(board: Board, enumerate = true): boolean {
16
- const adjacent = neighboursOf(board.settings);
17
- const open = board.clues.map(() => false);
18
- const known = new Set<number>();
19
- flood(board.clues, adjacent, open, [board.first]);
20
- while (open.filter(Boolean).length < activeCells(board.settings).length - board.settings.mines) {
21
- const visible: VisibleGame = {
22
- settings: board.settings, clues: board.clues.map((n, cell) => activeCell(board.settings, cell) ? open[cell] ? n : null : -2),
23
- marks: open.map((yes) => yes ? MARKS.open : MARKS.covered), status: STATUSES.playing,
24
- };
25
- const result = deduce(visible, known, enumerate);
26
- if (result.contradiction) return false;
27
- let changed = false;
28
- for (const cell of result.mines) {
29
- if (!board.mines[cell]) return false;
30
- if (!known.has(cell)) { known.add(cell); changed = true; }
31
- }
32
- if (result.safe.some((cell) => board.mines[cell])) return false;
33
- if (result.safe.some((cell) => !open[cell])) { flood(board.clues, adjacent, open, result.safe); changed = true; }
34
- if (!changed) return false;
35
- }
36
- return true;
16
+ const solver = new Solver(board.settings);
17
+ return solver.run(Int8Array.from(board.clues), board.first, enumerate).solved;
37
18
  }
38
19
 
39
- /** Deal after the first reveal. A seed fixes the whole candidate stream and the accepted board. */
20
+ /** Layouts the repair stage may try, per cell of the field. */
21
+ const REPAIRS_PER_CELL = 12;
22
+
23
+ /**
24
+ * Deal after the first reveal. A seed fixes the whole candidate stream and the accepted board.
25
+ *
26
+ * A no-guess deal first draws random layouts, as 0.1 and 0.2 did, so every board those versions dealt is still dealt.
27
+ * If none of them can be finished by deduction it takes the closest and repairs it: single mines are moved near the
28
+ * place the solver stopped until the solver finishes the whole field. The result is proved the same way either route.
29
+ */
40
30
  export function makeBoard(settings: Settings, first: number, options: GenerationOptions = {}): Board {
41
31
  if (!validSettings(settings) || !validCell(settings, first)) throw new GenerationError("settings", "Invalid board settings or opening cell.");
42
32
  const protectedCells = new Set([first, ...(settings.opening === "clear" ? neighbours(settings, first) : [])]);
43
- const available = Array.from({ length: settings.width * settings.height }, (_, cell) => cell).filter((cell) => validCell(settings, cell) && !protectedCells.has(cell));
33
+ const available = activeCells(settings).filter((cell) => !protectedCells.has(cell));
44
34
  if (available.length < settings.mines) throw new GenerationError("opening", "Too many mines for a safe opening at this cell.");
35
+ if (settings.noGuess && neighbours(settings, first).length === 0 && available.length > settings.mines)
36
+ throw new GenerationError("opening", "The opening cell touches no other cell, so no clue can follow from it. Open another cell.");
45
37
  const attempts = options.attempts ?? GENERATION_ATTEMPTS;
46
38
  if (!Number.isInteger(attempts) || attempts < 1 || attempts > 10_000) throw new GenerationError("settings", "Attempts must be between 1 and 10000.");
39
+ const repairs = options.repairs ?? (options.repair === false ? 0 : REPAIRS_PER_CELL * settings.width * settings.height);
40
+ if (!Number.isInteger(repairs) || repairs < 0 || repairs > 1_000_000) throw new GenerationError("settings", "Repairs must be between 0 and 1000000.");
41
+ const enumerate = options.enumerate ?? true;
47
42
  const random = seededRandom(settings.seed);
48
43
  const adjacent = neighboursOf(settings);
44
+ const solver = new Solver(settings, adjacent);
45
+ const cells = settings.width * settings.height;
46
+ const layout = new Uint8Array(cells), clues = new Int8Array(cells);
47
+ let best: Uint8Array | null = null, fewest = Infinity;
48
+ const board = (attempt: number): Board => ({
49
+ settings: { ...settings }, mines: Array.from(layout, Boolean), clues: Array.from(clues), first, attempt,
50
+ });
49
51
  for (let attempt = 0; attempt < (settings.noGuess ? attempts : 1); attempt += 1) {
50
- const places = new Set(shuffled(available, random).slice(0, settings.mines));
51
- const mines = available.length ? Array.from({ length: settings.width * settings.height }, (_, cell) => places.has(cell)) : [];
52
- const clues = mines.map((mine, cell) => !activeCell(settings, cell) ? -2 : mine ? -1 : adjacent[cell]!.filter((n) => mines[n]).length);
53
- const board: Board = { settings: { ...settings }, mines, clues, first, attempt };
54
- if (!settings.noGuess || isSolvable(board, options.enumerate ?? true)) return board;
52
+ layout.fill(0);
53
+ for (const cell of shuffled(available, random).slice(0, settings.mines)) layout[cell] = 1;
54
+ solver.clueFor(layout, clues);
55
+ if (!settings.noGuess) return board(attempt);
56
+ const report = solver.run(clues, first, enumerate);
57
+ if (report.solved) return board(attempt);
58
+ if (report.remaining < fewest) { fewest = report.remaining; best = layout.slice(); }
59
+ }
60
+ if (best !== null && repairs > 0) {
61
+ // A cell no chain of neighbours reaches from the opening can never be told by a clue. Make each a mine and leave it
62
+ // be: nobody has to find a mine to win, and nobody could find that one. Fewer mines than such cells: do not try.
63
+ const reached = new Set([first]);
64
+ for (const cell of reached) for (const n of adjacent[cell]!) reached.add(n);
65
+ const stranded = available.filter((cell) => !reached.has(cell));
66
+ if (stranded.length <= settings.mines) {
67
+ const reachable = available.filter((cell) => reached.has(cell));
68
+ const place = (): void => {
69
+ layout.fill(0);
70
+ for (const cell of stranded) layout[cell] = 1;
71
+ for (const cell of shuffled(reachable, random).slice(0, settings.mines - stranded.length)) layout[cell] = 1;
72
+ solver.clueFor(layout, clues);
73
+ };
74
+ // Begin from the closest of the random layouts, with the stranded cells made mines at the cost of other mines.
75
+ layout.set(best);
76
+ const movable = reachable.filter((cell) => layout[cell]);
77
+ for (const cell of shuffled(stranded.filter((c) => !layout[c]), random)) { const from = movable.pop(); layout[from!] = 0; layout[cell] = 1; }
78
+ solver.clueFor(layout, clues);
79
+ const outcome = repair(solver, layout, clues, first, new Set([...protectedCells, ...stranded]), random, repairs, enumerate, place);
80
+ if (outcome.solved) return board(attempts + outcome.tries);
81
+ }
55
82
  }
56
83
  throw new GenerationError("exhausted", "No verified board found within the work budget. Try another seed, fewer mines, or a different opening.");
57
84
  }
package/src/index.ts CHANGED
@@ -8,8 +8,13 @@ export * from "./deduce.ts";
8
8
  export * from "./keep.ts";
9
9
  export { seededRandom } from "./random.ts";
10
10
  /** Package version, kept in step with the release metadata. */
11
- export const VERSION = "0.2.1";
11
+ export const VERSION = "0.4.0";
12
12
 
13
13
  export { SHAPES, activeCell, activeCells } from "./shape.ts";
14
14
 
15
15
  export * from "./orthogonal.ts";
16
+ export { measureBoard } from "./measure.ts";
17
+ export type { Measure } from "./measure.ts";
18
+ export type { ProofKind, ProofTally } from "./solve.ts";
19
+ export { hugeSettings, levelNamed, levelSettings } from "./levels.ts";
20
+ export type { HugeSize, LevelSize } from "./levels.ts";
@@ -15,21 +15,39 @@ export const GRID_SPECS: Record<Grid, { offsets: readonly (readonly [number, num
15
15
  hex: { offsets: [[-1,0],[1,0],[0,-1],[1,-1],[-1,1],[0,1]], wrap: false },
16
16
  wrap: { offsets: [[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]], wrap: true },
17
17
  };
18
- /** Common minefield dimensions and mine counts. */
18
+ /** The four difficulty levels, easiest first. Each is a larger and denser field than the one before. */
19
+ export const LEVELS = ["easy", "medium", "hard", "extra-hard"] as const;
20
+ /** The 0.1 and 0.2 names for the first three levels. They are still accepted wherever a level is. */
21
+ export const LEVEL_ALIASES = { beginner: "easy", intermediate: "medium", expert: "hard" } as const;
22
+ /** Size and mine count of each level on a rectangular board. Shaped boards keep the size and the density. */
23
+ export const LEVEL_SIZES: Record<(typeof LEVELS)[number], { width: number; height: number; mines: number }> = {
24
+ easy: { width: 9, height: 9, mines: 10 },
25
+ medium: { width: 16, height: 16, mines: 40 },
26
+ hard: { width: 30, height: 16, mines: 99 },
27
+ "extra-hard": { width: 40, height: 24, mines: 240 },
28
+ };
29
+ /**
30
+ * The huge fields: four times the area of a 16×16 (the medium level), 1,024 to 1,152 squares, for a long solve. The same
31
+ * share of mines as a level, see `hugeSettings`. They are dealt, proved and drawn like any other field: a no-guess deal takes
32
+ * a few milliseconds to a tenth of a second here, and 2,400 squares is the most `validSettings` accepts.
33
+ */
34
+ export const HUGE_SIZES = [{ width: 32, height: 32 }, { width: 48, height: 24 }, { width: 24, height: 48 }] as const satisfies readonly { width: number; height: number }[];
35
+ /** Common minefield dimensions and mine counts. The levels, their older names, and two shapes of field. */
19
36
  export const PRESETS = {
20
- beginner: { width: 9, height: 9, mines: 10 },
21
- intermediate: { width: 16, height: 16, mines: 40 },
22
- expert: { width: 30, height: 16, mines: 99 },
37
+ ...LEVEL_SIZES,
38
+ beginner: LEVEL_SIZES.easy,
39
+ intermediate: LEVEL_SIZES.medium,
40
+ expert: LEVEL_SIZES.hard,
23
41
  wide: { width: 21, height: 9, mines: 24 },
24
42
  tall: { width: 9, height: 21, mines: 24 },
25
43
  } as const;
26
- /** Default beginner game, with a verified no-guess board and clear opening. */
27
- export const DEFAULT_SETTINGS: Settings = { ...PRESETS.beginner, grid: GRIDS.square, noGuess: true, opening: "clear", seed: 1 };
44
+ /** Default easy game, with a verified no-guess board and clear opening. */
45
+ export const DEFAULT_SETTINGS: Settings = { ...LEVEL_SIZES.easy, grid: GRIDS.square, noGuess: true, opening: "clear", seed: 1 };
28
46
  /** Largest width or height accepted by settings validation. */
29
47
  export const MAX_SIDE = 60;
30
48
  /** Largest total cell count accepted by settings validation. */
31
49
  export const MAX_CELLS = 2400;
32
- /** Default candidate-board budget for verified generation. */
50
+ /** Default number of random layouts tried before a no-guess deal falls back to repairing the closest one. */
33
51
  export const GENERATION_ATTEMPTS = 128;
34
52
  /** Largest frontier enumerated for exact deductions. */
35
53
  export const ENUMERATION_CELLS = 18;
@@ -1,5 +1,9 @@
1
1
  /** Neighbour topology used to count the clues around each cell. */
2
2
  export type Grid = "square" | "orthogonal" | "hex" | "wrap";
3
+ /** A difficulty level: easy, medium, hard or extra-hard. */
4
+ export type Level = "easy" | "medium" | "hard" | "extra-hard";
5
+ /** The 0.1 and 0.2 names for easy, medium and hard, still accepted wherever a level is. */
6
+ export type LevelAlias = "beginner" | "intermediate" | "expert";
3
7
  /** Current game state, including whether a mine has been hit. */
4
8
  export type Status = "ready" | "playing" | "won" | "lost";
5
9
  /** Player-facing state of one cell; the answer is never a mark. */
@@ -26,6 +30,7 @@ export type Board = {
26
30
  mines: readonly boolean[];
27
31
  clues: readonly number[];
28
32
  first: number;
33
+ /** Which candidate this deal was: below the `attempts` limit it is a random layout, at or above it a repaired one. */
29
34
  attempt: number;
30
35
  };
31
36
  /** Rules data includes the answer; never send it to a competitive client. Use visibleGame for hints and drawing. */
@@ -58,8 +63,12 @@ export type Deduction = {
58
63
  /** A conflicting clue, or a board with no consistent mine placement. */
59
64
  contradiction: boolean;
60
65
  };
61
- /** Work limits for seeded board generation and its no-guess check. */
62
- export type GenerationOptions = { attempts?: number; enumerate?: boolean };
66
+ /**
67
+ * Work limits for seeded board generation and its no-guess check. `attempts` is the number of random layouts tried
68
+ * first; `repairs` is how many single-mine moves the repair stage may try on the closest of them (0, or `repair:
69
+ * false`, keeps the 0.2 behaviour of giving up after the attempts); `enumerate` switches the exact small-frontier check.
70
+ */
71
+ export type GenerationOptions = { attempts?: number; repairs?: number; repair?: boolean; enumerate?: boolean };
63
72
  /** Supported interface copy locales. */
64
73
  export type Language = "en" | "ja";
65
74
  /** Board colours for drawing and mounted play. */
package/src/levels.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { HUGE_SIZES, LEVEL_ALIASES, LEVEL_SIZES, LEVELS } from "./jirai.constants.ts";
2
+ import { activeCells } from "./shape.ts";
3
+ import type { Grid, Level, LevelAlias, Settings } from "./jirai.types.ts";
4
+
5
+ /** Board size and mine count a level asks for. */
6
+ export type LevelSize = Pick<Settings, "width" | "height" | "mines">;
7
+
8
+ /**
9
+ * The level a name means, or null. Accepts `easy`, `medium`, `hard` and `extra-hard` (also written `extra hard`,
10
+ * `extra_hard` or `extraHard`, in any case), and the older `beginner`, `intermediate` and `expert`.
11
+ */
12
+ export function levelNamed(name: unknown): Level | null {
13
+ if (typeof name !== "string") return null;
14
+ const key = name.trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/^extrahard$/, "extra-hard");
15
+ if (Object.hasOwn(LEVEL_ALIASES, key)) return LEVEL_ALIASES[key as LevelAlias];
16
+ return (LEVELS as readonly string[]).includes(key) ? key as Level : null;
17
+ }
18
+
19
+ /**
20
+ * The size and mine count of a level. A rectangle gets the level's own numbers; a shaped board keeps the level's
21
+ * width and height and its density of mines over the cells that are left. Throws `RangeError` for a name that is no level.
22
+ */
23
+ export function levelSettings(level: Level | LevelAlias, board: { grid?: Grid; shape?: Settings["shape"] } = {}): LevelSize {
24
+ const named = levelNamed(level);
25
+ if (named === null) throw new RangeError(`Unknown level: ${String(level)}`);
26
+ const size = LEVEL_SIZES[named];
27
+ if ((board.shape ?? "rectangle") === "rectangle") return { ...size };
28
+ const probe = { ...size, grid: board.grid ?? "square", shape: board.shape, noGuess: true, opening: "clear", seed: 1 } as const;
29
+ const cells = activeCells(probe).length;
30
+ return { width: size.width, height: size.height, mines: Math.max(1, Math.min(cells - 10, Math.round(size.mines / (size.width * size.height) * cells))) };
31
+ }
32
+
33
+ /** The outline of a huge field: one of `HUGE_SIZES`' width and height. */
34
+ export type HugeSize = { width: number; height: number };
35
+
36
+ /**
37
+ * The size and mine count of a level on a huge field: a field of `HUGE_SIZES` (32 × 32 unless `size` says another of them),
38
+ * with the level's own share of mines over its squares. Easy is 12% mines, medium 16%, hard 21% and extra-hard 25%, as
39
+ * on the level's own field, and a heart, star or hexagon outline keeps that share over the squares it has left. Every
40
+ * field is still dealt and proved to need no guess, on every grid. Throws `RangeError` for a name that is no level or a size that is not huge.
41
+ */
42
+ export function hugeSettings(level: Level | LevelAlias, board: { grid?: Grid; shape?: Settings["shape"]; size?: HugeSize } = {}): LevelSize {
43
+ const named = levelNamed(level);
44
+ if (named === null) throw new RangeError(`Unknown level: ${String(level)}`);
45
+ const size = board.size ?? HUGE_SIZES[0];
46
+ if (!HUGE_SIZES.some((huge) => huge.width === size.width && huge.height === size.height)) throw new RangeError(`Not a huge size: ${size.width} × ${size.height}`);
47
+ const own = LEVEL_SIZES[named];
48
+ const probe = { width: size.width, height: size.height, mines: 1, grid: board.grid ?? "square", shape: board.shape, noGuess: true, opening: "clear", seed: 1 } as const;
49
+ const cells = activeCells(probe).length;
50
+ return { width: size.width, height: size.height, mines: Math.max(1, Math.min(cells - 10, Math.round(own.mines / (own.width * own.height) * cells))) };
51
+ }
package/src/measure.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { Solver } from "./solve.ts";
2
+ import type { ProofTally } from "./solve.ts";
3
+ import type { Board } from "./jirai.types.ts";
4
+
5
+ /** How demanding a dealt board is to solve by deduction, measured by solving it. */
6
+ export type Measure = {
7
+ /** Mines per playable cell. */
8
+ density: number;
9
+ /** Playable cells. */
10
+ cells: number;
11
+ /** Share of the safe cells the first reveal opens before any reasoning. */
12
+ opening: number;
13
+ /** Cells proved by each kind of reasoning: one clue, two clues together, the mine counter, or every arrangement of a small frontier. */
14
+ proofs: ProofTally;
15
+ /** Share of the playable cells proved by anything beyond one clue's count: the part of the board that needs multi-step reasoning. */
16
+ multiStep: number;
17
+ /** The longest chain of deductions, each resting on the one before. */
18
+ depth: number;
19
+ /** One number for ranking boards: higher is harder. Not a calibrated rating, but monotone in each part above. */
20
+ score: number;
21
+ /** The board can be finished by deduction alone. */
22
+ solvable: boolean;
23
+ };
24
+
25
+ /**
26
+ * Solve a dealt board from its opening and report what it took. The score is
27
+ * `100 × density + 100 × multiStep + depth ÷ 4`, so it rises with the crowding of the mines, with the share of the
28
+ * field that needs more than a single clue, and with how long the longest chain of reasoning runs. It is a way to
29
+ * put boards in order, not a rating of how long a person will take.
30
+ */
31
+ export function measureBoard(board: Board): Measure {
32
+ const solver = new Solver(board.settings);
33
+ const report = solver.run(Int8Array.from(board.clues), board.first, true);
34
+ const cells = solver.safeTotal + solver.mineTotal;
35
+ const density = solver.mineTotal / cells;
36
+ const { count, overlap, total, enumeration } = report.proved;
37
+ const multiStep = (overlap + total + enumeration) / cells;
38
+ const opening = solver.safeTotal === 0 ? 0 : report.free / solver.safeTotal;
39
+ const score = 100 * density + 100 * multiStep + report.depth / 4;
40
+ return {
41
+ density, cells, opening, proofs: { count, overlap, total, enumeration }, multiStep, depth: report.depth,
42
+ score: Math.round(score * 10) / 10, solvable: report.solved,
43
+ };
44
+ }
package/src/repair.ts ADDED
@@ -0,0 +1,88 @@
1
+ import type { Solver } from "./solve.ts";
2
+
3
+ /** What a repair run did: whether it reached a board the solver finishes, how many layouts it tried, and how many safe cells it left covered. */
4
+ export type RepairOutcome = { solved: boolean; tries: number; remaining: number };
5
+
6
+ /** How readily a move that leaves more safe cells covered is kept, to climb out of a dead end. Small: nearly all such moves are refused. */
7
+ const WARMTH = 0.3;
8
+ /** Tries without getting closer after which the search begins again from a new layout, at least. */
9
+ const PATIENCE = 1500;
10
+ /** How far from the stuck cell a mine may be moved from and to. */
11
+ const REACH = 2;
12
+
13
+ function pick<T>(items: readonly T[], random: () => number): T | undefined {
14
+ return items.length === 0 ? undefined : items[Math.floor(random() * items.length)];
15
+ }
16
+
17
+ /** Move a mine from `from` to `to`, keeping every clue in step. Calling it again with the arguments swapped undoes it. */
18
+ function move(solver: Solver, mines: Uint8Array, clues: Int8Array, from: number, to: number): void {
19
+ mines[from] = 0; mines[to] = 1;
20
+ for (const cell of [from, to]) {
21
+ const delta = cell === to ? 1 : -1;
22
+ for (const n of solver.adjacent[cell]!) if (!mines[n]) clues[n]! += delta;
23
+ }
24
+ clues[to] = -1;
25
+ let count = 0;
26
+ for (const n of solver.adjacent[from]!) if (mines[n]) count += 1;
27
+ clues[from] = count;
28
+ }
29
+
30
+ /**
31
+ * Make an unsolvable layout solvable by moving single mines next to the place the solver got stuck, never touching a
32
+ * pinned cell, and keeping a move when it leaves the solver no worse off (and now and then when it does, so that a
33
+ * dead end can be left). The search is counted in layouts tried, never in time, so a seed always gives the same board.
34
+ * `mines` and `clues` are changed in place and hold the answer when the outcome is solved.
35
+ */
36
+ export function repair(solver: Solver, mines: Uint8Array, clues: Int8Array, first: number, pinned: ReadonlySet<number>, random: () => number, budget: number, enumerate: boolean, restart: () => void): RepairOutcome {
37
+ const around = (cell: number, radius: number): number[] => {
38
+ const seen = new Set([cell]);
39
+ let ring = [cell];
40
+ for (let step = 0; step < radius; step += 1) {
41
+ const next: number[] = [];
42
+ for (const c of ring) for (const n of solver.adjacent[c]!) if (!seen.has(n)) { seen.add(n); next.push(n); }
43
+ ring = next;
44
+ }
45
+ return [...seen].filter((c) => !pinned.has(c));
46
+ };
47
+ let report = solver.run(clues, first, enumerate);
48
+ let tries = 0, closest = report.remaining, idle = 0;
49
+ const patience = Math.max(PATIENCE, 2 * solver.cells);
50
+ while (!report.solved && tries < budget) {
51
+ tries += 1;
52
+ const frontier: number[] = [], covered: number[] = [], cutOff: number[] = [];
53
+ for (let cell = 0; cell < solver.cells; cell += 1) {
54
+ if (solver.state[cell] !== 0) continue;
55
+ covered.push(cell);
56
+ if (solver.adjacent[cell]!.some((n) => solver.state[n] === 1)) frontier.push(cell);
57
+ else if (!mines[cell] && !pinned.has(cell)) cutOff.push(cell);
58
+ }
59
+ let from: number | undefined, to: number | undefined;
60
+ const lost = cutOff.length > 0 && random() < 0.5 ? pick(cutOff, random) : undefined;
61
+ if (lost !== undefined) {
62
+ // A safe cell no opened clue touches is walled in by mines. Either wall one in more, or take a wall mine away.
63
+ const walls = solver.adjacent[lost]!.filter((n) => mines[n] && !pinned.has(n));
64
+ if (walls.length > 0 && random() < 0.5) { from = pick(walls, random); to = pick(around(from!, REACH).filter((c) => !mines[c]), random); }
65
+ else { to = lost; from = pick(around(lost, REACH + 1).filter((c) => mines[c]), random); }
66
+ } else {
67
+ const focus = pick(frontier.length > 0 ? frontier : covered, random);
68
+ if (focus === undefined) break;
69
+ let near = around(focus, REACH);
70
+ from = pick(near.filter((c) => mines[c]), random);
71
+ if (from === undefined) { near = around(focus, REACH + 2); from = pick(near.filter((c) => mines[c]), random); }
72
+ to = pick(near.filter((c) => !mines[c]), random);
73
+ }
74
+ if (from === undefined || to === undefined) continue;
75
+ move(solver, mines, clues, from, to);
76
+ const next = solver.run(clues, first, enumerate);
77
+ const worse = next.remaining - report.remaining;
78
+ if (worse < 0 || (worse === 0 && next.unresolved <= report.unresolved) || (worse > 0 && random() < Math.exp(-worse / WARMTH))) report = next;
79
+ else move(solver, mines, clues, to, from);
80
+ if (report.remaining < closest) { closest = report.remaining; idle = 0; }
81
+ else if (++idle > patience) {
82
+ // Stuck for a long while in one corner of the search: begin again from a new layout.
83
+ restart();
84
+ report = solver.run(clues, first, enumerate); closest = report.remaining; idle = 0;
85
+ }
86
+ }
87
+ return { solved: report.solved, tries, remaining: report.remaining };
88
+ }
package/src/solve.ts ADDED
@@ -0,0 +1,253 @@
1
+ import { enumerateForced } from "./enumerate.ts";
2
+ import { neighboursOf } from "./grid.ts";
3
+ import { activeCell } from "./shape.ts";
4
+ import type { Constraint, Settings } from "./jirai.types.ts";
5
+
6
+ /** Why a cell was proved: one clue, two overlapping clues, the mine counter, or every arrangement of a small frontier. */
7
+ export type ProofKind = "count" | "overlap" | "total" | "enumeration";
8
+ /** Cells proved by each kind of reasoning. */
9
+ export type ProofTally = Record<ProofKind, number>;
10
+ /** What a run of the deduction solver found. */
11
+ export type SolveReport = {
12
+ /** Every safe cell was opened using only proved deductions. */
13
+ solved: boolean;
14
+ /** Safe cells still covered when the solver stopped; zero when solved. */
15
+ remaining: number;
16
+ /** Safe cells opened, including the free opening. */
17
+ opened: number;
18
+ /** Covered cells, safe or mine, nothing has been proved about. */
19
+ unresolved: number;
20
+ /** Cells opened by the first reveal and its flood, before any deduction. */
21
+ free: number;
22
+ /** Cells proved (safe or mine) by each kind of reasoning. */
23
+ proved: ProofTally;
24
+ /** The longest chain of deductions, each resting on the one before. */
25
+ depth: number;
26
+ };
27
+
28
+ const COVERED = 0, OPEN = 1, MINE = 2, OUTSIDE = 3;
29
+
30
+ /**
31
+ * The same deductions as `deduce` (one clue, two overlapping clues, the mine counter, exact enumeration of a
32
+ * small frontier), run to a fixed point over one board in a single pass instead of one deduction per scan of the
33
+ * whole field. A deduction found here is a deduction `deduce` would find; the order differs, the closure does not.
34
+ * Built once for a set of settings, then `run` as often as needed on different mine layouts.
35
+ */
36
+ export class Solver {
37
+ readonly adjacent: readonly (readonly number[])[];
38
+ readonly cells: number;
39
+ readonly safeTotal: number;
40
+ readonly mineTotal: number;
41
+ readonly state: Uint8Array;
42
+ private readonly start: Uint8Array;
43
+ private readonly need: Int8Array;
44
+ private readonly unknown: Int8Array;
45
+ private readonly chain: Int16Array;
46
+ private readonly dirty: Uint8Array;
47
+ private readonly searched: Uint8Array;
48
+ private readonly marks: Int32Array;
49
+ private readonly seen: Int32Array;
50
+ private readonly visit: Int32Array;
51
+ private readonly queue: number[] = [];
52
+ private readonly stack: number[] = [];
53
+ private clues: Int8Array = new Int8Array(0);
54
+ private stamp = 0;
55
+ private covered = 0;
56
+ private left = 0;
57
+ private opened = 0;
58
+ private free = 0;
59
+ private deepestMine = 0;
60
+ private depth = 0;
61
+ private broken = false;
62
+ private searching = true;
63
+ private proved: ProofTally = { count: 0, overlap: 0, total: 0, enumeration: 0 };
64
+
65
+ constructor(readonly settings: Settings, adjacent: readonly (readonly number[])[] = neighboursOf(settings)) {
66
+ this.adjacent = adjacent;
67
+ this.cells = settings.width * settings.height;
68
+ this.start = Uint8Array.from({ length: this.cells }, (_, cell) => activeCell(settings, cell) ? COVERED : OUTSIDE);
69
+ this.safeTotal = this.start.reduce((sum, state) => sum + (state === COVERED ? 1 : 0), 0) - settings.mines;
70
+ this.mineTotal = settings.mines;
71
+ this.state = new Uint8Array(this.cells);
72
+ this.need = new Int8Array(this.cells);
73
+ this.unknown = new Int8Array(this.cells);
74
+ this.chain = new Int16Array(this.cells);
75
+ this.dirty = new Uint8Array(this.cells);
76
+ this.searched = new Uint8Array(this.cells);
77
+ this.marks = new Int32Array(this.cells);
78
+ this.seen = new Int32Array(this.cells);
79
+ this.visit = new Int32Array(this.cells);
80
+ }
81
+
82
+ /** Clues of a layout: -1 for a mine, -2 outside the shape, otherwise the count of neighbouring mines. */
83
+ clueFor(mines: ArrayLike<number | boolean>, into: Int8Array = new Int8Array(this.cells)): Int8Array {
84
+ for (let cell = 0; cell < this.cells; cell += 1) {
85
+ if (this.start[cell] === OUTSIDE) { into[cell] = -2; continue; }
86
+ if (mines[cell]) { into[cell] = -1; continue; }
87
+ let count = 0;
88
+ for (const n of this.adjacent[cell]!) if (mines[n]) count += 1;
89
+ into[cell] = count;
90
+ }
91
+ return into;
92
+ }
93
+
94
+ /** Play the opening at `first` and every deduction after it. `clues` is read, never changed. */
95
+ run(clues: Int8Array, first: number, enumerate = true): SolveReport {
96
+ this.clues = clues;
97
+ this.state.set(this.start); this.need.fill(0); this.unknown.fill(0); this.chain.fill(0);
98
+ this.dirty.fill(0); this.searched.fill(0); this.queue.length = 0;
99
+ this.covered = this.safeTotal + this.mineTotal; this.left = this.mineTotal;
100
+ this.opened = 0; this.free = 0; this.deepestMine = 0; this.depth = 0; this.broken = false;
101
+ this.proved = { count: 0, overlap: 0, total: 0, enumeration: 0 };
102
+ if ((clues[first] ?? -1) < 0) return this.report();
103
+ this.reveal(first, 0, null);
104
+ this.free = this.opened;
105
+ for (;;) {
106
+ while (this.queue.length > 0 && !this.broken) {
107
+ const cell = this.queue.pop()!;
108
+ this.dirty[cell] = 0;
109
+ while (this.step(cell)) { /* a clue may settle more than once */ }
110
+ }
111
+ if (this.broken || this.opened === this.safeTotal || this.covered === 0) break;
112
+ if (this.counter()) continue;
113
+ if (enumerate && this.enumerate()) continue;
114
+ break;
115
+ }
116
+ return this.report();
117
+ }
118
+
119
+ private report(): SolveReport {
120
+ const solved = !this.broken && this.opened === this.safeTotal;
121
+ return { solved, remaining: this.safeTotal - this.opened, unresolved: this.covered, opened: this.opened, free: this.free, proved: { ...this.proved }, depth: this.depth };
122
+ }
123
+
124
+ private touch(cell: number): void {
125
+ this.searched[cell] = 0;
126
+ if (!this.dirty[cell]) { this.dirty[cell] = 1; this.queue.push(cell); }
127
+ }
128
+
129
+ /** Open a cell known to be safe, and flood through every zero. `kind` null is the free opening. */
130
+ private reveal(start: number, depth: number, kind: ProofKind | null): void {
131
+ const stack = this.stack;
132
+ stack.length = 0; stack.push(start);
133
+ let first = true;
134
+ while (stack.length > 0) {
135
+ const cell = stack.pop()!;
136
+ if (this.state[cell] !== COVERED) continue;
137
+ if (this.clues[cell]! < 0) { this.broken = true; return; }
138
+ if (first && kind !== null) { this.proved[kind] += 1; if (depth > this.depth) this.depth = depth; }
139
+ first = false;
140
+ this.state[cell] = OPEN; this.covered -= 1; this.opened += 1;
141
+ let mines = 0, unknown = 0;
142
+ for (const n of this.adjacent[cell]!) {
143
+ const s = this.state[n];
144
+ if (s === MINE) mines += 1; else if (s === COVERED) unknown += 1;
145
+ else if (s === OPEN) { this.unknown[n]! -= 1; if (depth > this.chain[n]!) this.chain[n] = depth; this.touch(n); }
146
+ }
147
+ this.need[cell] = this.clues[cell]! - mines; this.unknown[cell] = unknown; this.chain[cell] = depth;
148
+ if (this.clues[cell] === 0) { for (const n of this.adjacent[cell]!) if (this.state[n] === COVERED) stack.push(n); }
149
+ else if (unknown > 0) this.touch(cell);
150
+ }
151
+ }
152
+
153
+ private flag(cell: number, depth: number, kind: ProofKind): void {
154
+ if (this.state[cell] !== COVERED) return;
155
+ if (this.clues[cell]! >= 0) { this.broken = true; return; }
156
+ this.state[cell] = MINE; this.covered -= 1; this.left -= 1;
157
+ this.proved[kind] += 1; if (depth > this.depth) this.depth = depth;
158
+ if (depth > this.deepestMine) this.deepestMine = depth;
159
+ for (const n of this.adjacent[cell]!) if (this.state[n] === OPEN) {
160
+ this.unknown[n]! -= 1; this.need[n]! -= 1; if (depth > this.chain[n]!) this.chain[n] = depth; this.touch(n);
161
+ }
162
+ }
163
+
164
+ private settle(cells: readonly number[], safe: boolean, depth: number, kind: ProofKind): void {
165
+ for (const cell of cells) { if (safe) this.reveal(cell, depth, kind); else this.flag(cell, depth, kind); }
166
+ }
167
+
168
+ /** One deduction from the clue at `cell` alone, or from it and an overlapping clue. */
169
+ private step(cell: number): boolean {
170
+ if (this.broken || this.state[cell] !== OPEN || this.unknown[cell] === 0) return false;
171
+ const around = this.adjacent[cell]!;
172
+ const unknown = this.unknown[cell]!, need = this.need[cell]!;
173
+ if (need < 0 || need > unknown) { this.broken = true; return false; }
174
+ const depth = this.chain[cell]! + 1;
175
+ if (need === 0 || need === unknown) {
176
+ this.settle(around.filter((n) => this.state[n] === COVERED), need === 0, depth, "count");
177
+ return true;
178
+ }
179
+ const mine = ++this.stamp;
180
+ for (const n of around) if (this.state[n] === COVERED) this.marks[n] = mine;
181
+ const compared = ++this.stamp;
182
+ for (const x of around) {
183
+ if (this.state[x] !== COVERED) continue;
184
+ for (const other of this.adjacent[x]!) {
185
+ if (other === cell || this.state[other] !== OPEN || this.unknown[other] === 0 || this.seen[other] === compared) continue;
186
+ this.seen[other] = compared;
187
+ let common = 0;
188
+ for (const y of this.adjacent[other]!) if (this.state[y] === COVERED && this.marks[y] === mine) common += 1;
189
+ const there = this.unknown[other]!;
190
+ let rest: number[], mines: number;
191
+ if (common === there && there < unknown) {
192
+ rest = around.filter((n) => this.state[n] === COVERED && !this.adjacent[other]!.includes(n)); mines = need - this.need[other]!;
193
+ } else if (common === unknown && unknown < there) {
194
+ rest = this.adjacent[other]!.filter((n) => this.state[n] === COVERED && this.marks[n] !== mine); mines = this.need[other]! - need;
195
+ } else continue;
196
+ if (mines < 0 || mines > rest.length) { this.broken = true; return false; }
197
+ if (mines !== 0 && mines !== rest.length) continue;
198
+ this.settle(rest, mines === 0, 1 + Math.max(depth - 1, this.chain[other]!), "overlap");
199
+ return true;
200
+ }
201
+ }
202
+ return false;
203
+ }
204
+
205
+ /** The mine counter: nothing left to find, everything left a mine, or a clue that accounts for all that remain. */
206
+ private counter(): boolean {
207
+ const covered: number[] = [];
208
+ for (let cell = 0; cell < this.cells; cell += 1) if (this.state[cell] === COVERED) covered.push(cell);
209
+ if (covered.length === 0) return false;
210
+ const depth = this.deepestMine + 1;
211
+ if (this.left === 0 || this.left === covered.length) { this.settle(covered, this.left === 0, depth, "total"); return true; }
212
+ for (let cell = 0; cell < this.cells; cell += 1) {
213
+ if (this.state[cell] !== OPEN || this.unknown[cell] === 0) continue;
214
+ const outside = covered.length - this.unknown[cell]!, mines = this.left - this.need[cell]!;
215
+ if (outside === 0 || (mines !== 0 && mines !== outside)) continue;
216
+ const mark = ++this.stamp;
217
+ for (const n of this.adjacent[cell]!) if (this.state[n] === COVERED) this.marks[n] = mark;
218
+ this.settle(covered.filter((n) => this.marks[n] !== mark), mines === 0, 1 + Math.max(depth - 1, this.chain[cell]!), "total");
219
+ return true;
220
+ }
221
+ return false;
222
+ }
223
+
224
+ /**
225
+ * Exact enumeration of every frontier small enough, as `enumerateForced` does. Every component is read from the
226
+ * same position and the answers are applied together, exactly as one `deduce` call does, so that this solver and
227
+ * the hint engine finish the same boards: with a cap on the size of a frontier, the order of enumerating matters.
228
+ */
229
+ private enumerate(): boolean {
230
+ const round = ++this.stamp;
231
+ const found: { mines: number[]; safe: number[]; depth: number }[] = [];
232
+ for (let start = 0; start < this.cells; start += 1) {
233
+ if (this.state[start] !== OPEN || this.unknown[start] === 0 || this.visit[start] === round) continue;
234
+ const clues = [start]; this.visit[start] = round;
235
+ const cells = new Set<number>();
236
+ for (let at = 0; at < clues.length; at += 1) for (const x of this.adjacent[clues[at]!]!) {
237
+ if (this.state[x] !== COVERED || cells.has(x)) continue;
238
+ cells.add(x);
239
+ for (const other of this.adjacent[x]!) if (this.state[other] === OPEN && this.visit[other] !== round) { this.visit[other] = round; clues.push(other); }
240
+ }
241
+ if (cells.size > 18 || clues.every((c) => this.searched[c])) continue;
242
+ clues.sort((a, b) => a - b);
243
+ const constraints: Constraint[] = clues.map((c) => ({ cells: this.adjacent[c]!.filter((n) => this.state[n] === COVERED), mines: this.need[c]!, sources: [c] }));
244
+ const result = enumerateForced(constraints);
245
+ if (result.contradiction) { this.broken = true; return false; }
246
+ if (result.safe.length === 0 && result.mines.length === 0) { for (const c of clues) this.searched[c] = 1; continue; }
247
+ found.push({ mines: [...result.mines], safe: [...result.safe], depth: 1 + clues.reduce((most, c) => Math.max(most, this.chain[c]!), 0) });
248
+ }
249
+ for (const one of found) this.settle(one.mines, false, one.depth, "enumeration");
250
+ for (const one of found) this.settle(one.safe, true, one.depth, "enumeration");
251
+ return found.length > 0;
252
+ }
253
+ }