File size: 9,701 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/**
 * 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;
}