// Word Search generator — the Rail Edition puzzle book. // // generatePuzzle({ difficulty, theme, seed }) → // { difficulty, theme, themeLabel, ink, size, words, placements, grid, // message, messageLetters, facts, seed } // // A puzzle is a square grid with a chapter's words hidden along straight lines. // The grid is packed (crossings preferred) until the cells no word uses — read // left→right, top→bottom — number exactly the letters of a secret message; // those leftover cells then spell it. So there are no random filler letters. // // Every listed word occurs exactly once in the finished grid (any of the 8 // directions, either way round), no listed word contains another, and only the // difficulty's directions are used. // // With a numeric seed the result is fully deterministic (the Daily): the module // `rand` is swapped for a seeded RNG for the duration of the call and the search // is bounded by an attempt count rather than the clock. import { THEMES, CHAPTER_ORDER, JOURNEY_MESSAGES, messageLetters } from './wordSearchThemes.js'; // [rowDelta, colDelta] const E = [0, 1], S = [1, 0], SE = [1, 1], NE = [-1, 1]; const W = [0, -1], N = [-1, 0], SW = [1, -1], NW = [-1, -1]; export const ALL_DIRS = [E, S, SE, NE, W, N, SW, NW]; // band = allowed leftover (message) length; words = how many words to hide. export const DIFFICULTY = { easy: { id: 'easy', size: 10, dirs: [E, S], band: [14, 30], words: [9, 13], maxLen: 10 }, medium: { id: 'medium', size: 12, dirs: [E, S, SE, NE], band: [18, 42], words: [12, 18], maxLen: 12 }, hard: { id: 'hard', size: 14, dirs: ALL_DIRS, band: [26, 56], words: [16, 26], maxLen: 12 }, expert: { id: 'expert', size: 16, dirs: ALL_DIRS, band: [40, 80], words: [22, 36], maxLen: 12 }, }; export const DIFFICULTIES = Object.keys(DIFFICULTY); const MAX_SEEDED_ATTEMPTS = 400; const DEADLINE_MS = 1500; // The generator's only randomness (swapped for a seeded RNG during seeded calls). let rand = Math.random; function makeRng(seed) { let a = seed >>> 0; return () => { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } const pick = (arr) => arr[Math.floor(rand() * arr.length)]; function shuffle(arr) { const a = [...arr]; for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(rand() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } const reverse = (w) => [...w].reverse().join(''); const clash = (a, b) => a.includes(b) || b.includes(a) || a.includes(reverse(b)) || b.includes(reverse(a)); function resolveDifficulty(id) { return DIFFICULTY[String(id ?? '').toLowerCase()] ?? DIFFICULTY.medium; } function resolveTheme(id) { const key = String(id ?? 'random').toLowerCase(); if (THEMES[key]) return key; return pick(CHAPTER_ORDER); } // Group message phrases by letter count. function byLength(list) { const m = new Map(); for (const text of list) { const n = messageLetters(text).length; if (!m.has(n)) m.set(n, []); m.get(n).push(text); } return m; } // Every legal placement of `word` (each adds at least one new cell). function placementsFor(grid, size, word, dirs) { const out = []; const L = word.length; for (const [dr, dc] of dirs) { const rMin = dr < 0 ? L - 1 : 0, rMax = dr > 0 ? size - L : size - 1; const cMin = dc < 0 ? L - 1 : 0, cMax = dc > 0 ? size - L : size - 1; for (let r = rMin; r <= rMax; r++) { for (let c = cMin; c <= cMax; c++) { let fresh = 0, ok = true; for (let i = 0; i < L; i++) { const g = grid[r + dr * i][c + dc * i]; if (g === '') fresh++; else if (g !== word[i]) { ok = false; break; } } if (ok && fresh > 0) out.push({ row: r, col: c, dir: [dr, dc], fresh }); } } } return out; } // How many distinct times `word` appears in the grid (all 8 directions, either // way round; a palindrome found both ways in the same cells counts once). export function countOccurrences(rows, word) { const size = rows.length; const L = word.length; const seen = new Set(); const targets = [word, reverse(word)]; for (const [dr, dc] of ALL_DIRS) { for (let r = 0; r < size; r++) { for (let c = 0; c < size; c++) { const er = r + dr * (L - 1), ec = c + dc * (L - 1); if (er < 0 || er >= size || ec < 0 || ec >= size) continue; let s = ''; for (let i = 0; i < L; i++) s += rows[r + dr * i][c + dc * i]; if (targets.includes(s)) { const a = `${r},${c}`, b = `${er},${ec}`; seen.add(a < b ? `${a}|${b}` : `${b}|${a}`); } } } } return seen.size; } // One packing attempt. Returns the finished puzzle core or null. function attempt(cfg, themeKey, themeLens, journeyLens) { const { size, dirs, band: [lo, hi], words: [wMin, wMax], maxLen } = cfg; const theme = THEMES[themeKey]; const grid = Array.from({ length: size }, () => Array(size).fill('')); let empty = size * size; const placed = []; // Longest words first (they're hardest to fit), with some jitter for variety. let pool = shuffle(Object.keys(theme.words).filter(w => w.length <= Math.min(size, maxLen))) .map(w => ({ w, k: w.length + rand() * 3 })) .sort((a, b) => b.k - a.k) .map(o => o.w); const apply = (word, p) => { for (let i = 0; i < word.length; i++) grid[p.row + p.dir[0] * i][p.col + p.dir[1] * i] = word[i]; empty -= p.fresh; placed.push({ word, row: p.row, col: p.col, dir: p.dir }); pool = pool.filter(w => w !== word && !clash(w, word)); }; const fits = (n) => n >= lo && n <= hi; for (;;) { if (placed.length >= wMin - 1 && empty <= hi + 12) { // Try to land the leftover count exactly on a message length with one // more word. Chapter phrases always; the journey phrases only once the // grid is nearly out of room or words. const lastChance = placed.length + 3 >= wMax || empty - lo < 8 || pool.length < 4; for (const lens of lastChance ? [themeLens, journeyLens] : [themeLens]) { const options = []; for (const word of pool) { for (const p of placementsFor(grid, size, word, dirs)) { const left = empty - p.fresh; if (fits(left) && lens.has(left)) options.push({ word, p, left }); } } if (options.length && placed.length + 1 >= wMin && placed.length + 1 <= wMax) { const o = pick(options); apply(o.word, o.p); return { grid, placed, lens }; } } if (placed.length >= wMin && fits(empty)) { if (themeLens.has(empty)) return { grid, placed, lens: themeLens }; if (lastChance && journeyLens.has(empty)) return { grid, placed, lens: journeyLens }; } } if (placed.length >= wMax || empty < lo || !pool.length) return null; // An ordinary step: the first word in the pool that fits, at a placement // that reuses as many letters as possible (with a little randomness). let done = false; while (pool.length && !done) { const word = pool[0]; const ps = placementsFor(grid, size, word, dirs); if (!ps.length) { pool.shift(); continue; } let best = null, bestScore = Infinity; for (const p of ps) { const score = p.fresh + rand() * 2.2; if (score < bestScore) { bestScore = score; best = p; } } apply(word, best); done = true; } if (!done) return null; } } export function generatePuzzle({ difficulty, theme, seed = null } = {}) { const seeded = seed != null && Number.isFinite(Number(seed)); const prevRand = rand; if (seeded) rand = makeRng(Number(seed)); try { const cfg = resolveDifficulty(difficulty); const themeKey = resolveTheme(theme); const info = THEMES[themeKey]; const themeMsgs = byLength(info.messages); const journeyMsgs = byLength(JOURNEY_MESSAGES); const themeLens = new Set(themeMsgs.keys()); const journeyLens = new Set(journeyMsgs.keys()); const deadline = seeded ? Infinity : Date.now() + DEADLINE_MS; for (let n = 0; seeded ? n < MAX_SEEDED_ATTEMPTS : (n < 40 || Date.now() < deadline); n++) { const res = attempt(cfg, themeKey, themeLens, journeyLens); if (!res) continue; const { grid, placed } = res; // leftover cells in reading order const leftover = []; for (let r = 0; r < cfg.size; r++) for (let c = 0; c < cfg.size; c++) if (grid[r][c] === '') leftover.push([r, c]); const msgs = (res.lens === themeLens ? themeMsgs : journeyMsgs).get(leftover.length); if (!msgs) continue; const message = pick(msgs); const letters = messageLetters(message); leftover.forEach(([r, c], i) => { grid[r][c] = letters[i]; }); const rows = grid.map(row => row.join('')); if (!placed.every(p => countOccurrences(rows, p.word) === 1)) continue; const words = placed.map(p => p.word).sort(); const facts = {}; for (const w of words) facts[w] = info.words[w]; return { difficulty: cfg.id, theme: themeKey, themeLabel: info.label, ink: info.ink, size: cfg.size, words, placements: placed, grid: rows, message, messageLetters: letters, facts, seed: seeded ? Number(seed) : null, }; } throw new Error(`wordsearch: could not build a ${cfg.id} ${themeKey} puzzle`); } finally { rand = prevRand; } } export function listThemes() { return CHAPTER_ORDER.map((id, i) => ({ id, label: THEMES[id].label, ink: THEMES[id].ink, chapter: i + 1 })); }