@johnmorrisdotca/jirai 0.2.1 → 0.3.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/CHANGELOG.md +8 -0
- package/README.md +50 -4
- package/dist/generate.d.ts +7 -1
- package/dist/generate.js +74 -43
- package/dist/index.d.ts +6 -1
- package/dist/index.js +3 -1
- package/dist/jirai.constants.d.ts +46 -12
- package/dist/jirai.constants.js +19 -7
- package/dist/jirai.types.d.ts +12 -1
- package/dist/levels.d.ts +16 -0
- package/dist/levels.js +29 -0
- package/dist/measure.d.ts +28 -0
- package/dist/measure.js +21 -0
- package/dist/repair.d.ts +14 -0
- package/dist/repair.js +112 -0
- package/dist/solve.d.ts +79 -0
- package/dist/solve.js +336 -0
- package/package.json +3 -2
- package/src/generate.ts +60 -33
- package/src/index.ts +6 -1
- package/src/jirai.constants.ts +19 -7
- package/src/jirai.types.ts +11 -2
- package/src/levels.ts +31 -0
- package/src/measure.ts +44 -0
- package/src/repair.ts +88 -0
- package/src/solve.ts +253 -0
- package/src/version.test.js +9 -0
package/src/jirai.constants.ts
CHANGED
|
@@ -15,21 +15,33 @@ 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
|
-
/**
|
|
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
|
+
/** Common minefield dimensions and mine counts. The levels, their older names, and two shapes of field. */
|
|
19
30
|
export const PRESETS = {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
31
|
+
...LEVEL_SIZES,
|
|
32
|
+
beginner: LEVEL_SIZES.easy,
|
|
33
|
+
intermediate: LEVEL_SIZES.medium,
|
|
34
|
+
expert: LEVEL_SIZES.hard,
|
|
23
35
|
wide: { width: 21, height: 9, mines: 24 },
|
|
24
36
|
tall: { width: 9, height: 21, mines: 24 },
|
|
25
37
|
} as const;
|
|
26
|
-
/** Default
|
|
27
|
-
export const DEFAULT_SETTINGS: Settings = { ...
|
|
38
|
+
/** Default easy game, with a verified no-guess board and clear opening. */
|
|
39
|
+
export const DEFAULT_SETTINGS: Settings = { ...LEVEL_SIZES.easy, grid: GRIDS.square, noGuess: true, opening: "clear", seed: 1 };
|
|
28
40
|
/** Largest width or height accepted by settings validation. */
|
|
29
41
|
export const MAX_SIDE = 60;
|
|
30
42
|
/** Largest total cell count accepted by settings validation. */
|
|
31
43
|
export const MAX_CELLS = 2400;
|
|
32
|
-
/** Default
|
|
44
|
+
/** Default number of random layouts tried before a no-guess deal falls back to repairing the closest one. */
|
|
33
45
|
export const GENERATION_ATTEMPTS = 128;
|
|
34
46
|
/** Largest frontier enumerated for exact deductions. */
|
|
35
47
|
export const ENUMERATION_CELLS = 18;
|
package/src/jirai.types.ts
CHANGED
|
@@ -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
|
-
/**
|
|
62
|
-
|
|
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,31 @@
|
|
|
1
|
+
import { 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
|
+
}
|
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
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { expect, it } from "vitest";
|
|
3
|
+
import { VERSION } from "./index.ts";
|
|
4
|
+
|
|
5
|
+
it("names one version in the package, the library and the changelog", () => {
|
|
6
|
+
const pkg = JSON.parse(readFileSync("package.json", "utf8"));
|
|
7
|
+
expect(VERSION).toBe(pkg.version);
|
|
8
|
+
expect(readFileSync("CHANGELOG.md", "utf8")).toMatch(new RegExp(`^## \\[${pkg.version.replaceAll(".", "\\.")}\\] - \\d{4}-\\d{2}-\\d{2}$`, "m"));
|
|
9
|
+
});
|