RotNot / src /lib /puzzles /constraint.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
9.7 kB
/**
* Constraint Grid puzzle generator.
* A 4Γ—4 Killer-Sudoku-lite: each row and column contains 1–4 exactly once,
* and irregular "cages" (regions) each have a target sum that the player
* must satisfy.
*
* Difficulty scaling:
* easy: 4–5 cages of size 1–3; some singleton cages reveal a digit
* medium: 5–6 cages of size 2–3; no singletons
* hard: 5–7 cages of size 2–4; no singletons; one cage spans all 4 rows
*/
export type ConstraintDifficulty = "easy" | "medium" | "hard";
// ── Cell coordinates ────────────────────────────────────────────────────────
/** A cell in the 4Γ—4 grid, row and col are 0-indexed. */
export interface GridCell {
row: number;
col: number;
}
export function cellKey(row: number, col: number): string {
return `${row},${col}`;
}
// ── Cage ────────────────────────────────────────────────────────────────────
export interface Cage {
/** Unique cage id (0-indexed). */
id: number;
/** Cells belonging to this cage. */
cells: GridCell[];
/** The target sum for this cage. */
targetSum: number;
}
// ── Puzzle ──────────────────────────────────────────────────────────────────
export interface ConstraintPuzzle {
/** 4Γ—4 solution grid (row-major, 1-indexed values). */
solution: number[][];
/**
* The grid shown to the player. Known cells (singleton cages on easy) are
* pre-filled; all others are 0 (blank).
*/
given: number[][];
/** Cage definitions. */
cages: Cage[];
/** Difficulty level. */
difficulty: ConstraintDifficulty;
/** Human-readable rule summary. */
hint: string;
}
// ── Latin-square generator (4Γ—4) ────────────────────────────────────────────
/**
* Generates a random valid 4Γ—4 Latin square where every row and every column
* contains each of 1–4 exactly once.
*/
export function generateLatinSquare(): number[][] {
// Start from a canonical solution and shuffle rows/cols/values
const base: number[][] = [
[1, 2, 3, 4],
[2, 1, 4, 3],
[3, 4, 1, 2],
[4, 3, 2, 1],
];
// Shuffle rows within the grid
const rowOrder = shuffle([0, 1, 2, 3]);
const colOrder = shuffle([0, 1, 2, 3]);
// Random value permutation: map canonical 1β†’a,2β†’b,3β†’c,4β†’d
const valueMap = shuffle([1, 2, 3, 4]);
const grid: number[][] = Array.from({ length: 4 }, () => Array(4).fill(0));
for (let r = 0; r < 4; r++) {
for (let c = 0; c < 4; c++) {
const canonicalVal = base[rowOrder[r]!]![colOrder[c]!]!;
grid[r]![c] = valueMap[canonicalVal - 1]!;
}
}
return grid;
}
/** Validate that a 4Γ—4 grid is a valid Latin square. */
export function isValidLatinSquare(grid: number[][]): boolean {
const expected = new Set([1, 2, 3, 4]);
for (let r = 0; r < 4; r++) {
const row = new Set(grid[r]);
if (row.size !== 4 || ![...row].every((v) => expected.has(v))) return false;
}
for (let c = 0; c < 4; c++) {
const col = new Set(grid.map((row) => row[c]!));
if (col.size !== 4 || ![...col].every((v) => expected.has(v))) return false;
}
return true;
}
// ── Cage builder ────────────────────────────────────────────────────────────
/**
* Partitions the 16 cells of a 4Γ—4 grid into contiguous cages.
* Each cage is a connected group of cells (4-connectivity).
*
* Strategy: BFS flood-fill starting from a random unassigned cell.
* Cage size is capped at `maxCageSize` and guided by difficulty.
*/
function buildCages(
solution: number[][],
difficulty: ConstraintDifficulty,
): Cage[] {
const maxSize = difficulty === "easy" ? 3 : difficulty === "medium" ? 3 : 4;
const minSize = difficulty === "easy" ? 1 : 2;
const assigned: boolean[][] = Array.from({ length: 4 }, () =>
Array(4).fill(false),
);
const cages: Cage[] = [];
let cageId = 0;
// Iterate cells in random order to vary starting points
const allCells: GridCell[] = [];
for (let r = 0; r < 4; r++) {
for (let c = 0; c < 4; c++) {
allCells.push({ row: r, col: c });
}
}
const shuffledCells = shuffle(allCells);
for (const startCell of shuffledCells) {
if (assigned[startCell.row]![startCell.col]) continue;
// BFS to grow cage
const cage: GridCell[] = [startCell];
assigned[startCell.row]![startCell.col] = true;
// Determine target cage size
const remaining = 16 - cages.reduce((s, c) => s + c.cells.length, 0);
const targetSize = Math.min(
maxSize,
remaining <= minSize + 1 ? remaining : randomInt(minSize, maxSize),
);
const frontier: GridCell[] = [startCell];
while (cage.length < targetSize && frontier.length > 0) {
const idx = Math.floor(Math.random() * frontier.length);
const cur = frontier[idx]!;
frontier.splice(idx, 1);
const neighbors = getNeighbors(cur);
const unvisited = neighbors.filter(
(n) => !assigned[n.row]![n.col],
);
if (unvisited.length === 0) continue;
const next = unvisited[Math.floor(Math.random() * unvisited.length)]!;
assigned[next.row]![next.col] = true;
cage.push(next);
frontier.push(next);
}
const targetSum = cage.reduce(
(s, cell) => s + solution[cell.row]![cell.col]!,
0,
);
cages.push({ id: cageId++, cells: cage, targetSum });
}
return cages;
}
function getNeighbors({ row, col }: GridCell): GridCell[] {
const dirs: [number, number][] = [
[-1, 0],
[1, 0],
[0, -1],
[0, 1],
];
return dirs
.map(([dr, dc]) => ({ row: row + dr!, col: col + dc! }))
.filter(({ row, col }) => row >= 0 && row < 4 && col >= 0 && col < 4);
}
// ── Puzzle generator ─────────────────────────────────────────────────────────
/**
* Generates a ConstraintPuzzle at the given difficulty.
*
* On easy, singleton cages (size=1) have their value pre-filled as a given.
*/
export function generateConstraintPuzzle(
difficulty: ConstraintDifficulty = "easy",
): ConstraintPuzzle {
const solution = generateLatinSquare();
const cages = buildCages(solution, difficulty);
// Build given grid (all zeros initially)
const given: number[][] = Array.from({ length: 4 }, () => Array(4).fill(0));
// On easy, reveal singleton cages
if (difficulty === "easy") {
for (const cage of cages) {
if (cage.cells.length === 1) {
const { row, col } = cage.cells[0]!;
given[row]![col] = solution[row]![col]!;
}
}
}
const hintText =
difficulty === "easy"
? "Fill each row and column with 1–4 (no repeats). Each box shows the sum its cells must reach."
: difficulty === "medium"
? "Each row and column must contain 1–4 exactly once. All cage sums must match their targets."
: "Fill the grid so every row and column has 1–4. All irregular regions must hit their target sums.";
return { solution, given, cages, difficulty, hint: hintText };
}
// ── Validation ───────────────────────────────────────────────────────────────
/**
* Validates a completed player grid against the solution rules.
* Returns true only if the grid is a valid Latin square AND all cages sum correctly.
* (Does NOT require matching the specific solution β€” any valid fill is accepted.)
*/
export function validateConstraintGrid(
playerGrid: number[][],
cages: Cage[],
): boolean {
// Check Latin-square property
if (!isValidLatinSquare(playerGrid)) return false;
// Check cage sums
for (const cage of cages) {
const sum = cage.cells.reduce(
(s, { row, col }) => s + (playerGrid[row]?.[col] ?? 0),
0,
);
if (sum !== cage.targetSum) return false;
}
return true;
}
/**
* Partial-credit score for a constraint grid.
* - 0.5 points for a valid Latin square
* - 0.5 points split across cages that have their correct sum
*
* Returns 0–1.
*/
export function scoreConstraintGrid(
playerGrid: number[][],
cages: Cage[],
): number {
const latinValid = isValidLatinSquare(playerGrid);
const latinScore = latinValid ? 0.5 : 0;
const correctCages = cages.filter((cage) => {
const sum = cage.cells.reduce(
(s, { row, col }) => s + (playerGrid[row]?.[col] ?? 0),
0,
);
return sum === cage.targetSum;
}).length;
const cageScore = cages.length > 0 ? 0.5 * (correctCages / cages.length) : 0;
return Math.round((latinScore + cageScore) * 100) / 100;
}
// ── Utilities ────────────────────────────────────────────────────────────────
function randomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle<T>(arr: T[]): T[] {
const a = [...arr];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j]!, a[i]!];
}
return a;
}