fertig-classic-games/tools/buildBeeWords.js

192 lines
8.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Builds data/wordlists/spellingbee-answers.txt — the curated ANSWER list the
// Spelling Bee generator builds puzzles from (see src/words/spellingBeeEngine.js).
//
// Every ENABLE word that fits a hive is still ACCEPTED in-game; this list only
// decides which words COUNT toward the goal (and which pangrams a puzzle may be
// built around). Words not on it become "Rare Finds" — bonus points, never
// required. Output lines are `WORD<TAB>tier`:
// core everyday words (Easy hives use only these)
// familiar words most adults know (Normal + Hard add these)
//
// Tiering is ENABLE ∩ the Norvig web word-frequency list, with length-aware rank
// cutoffs, plus an inflection rule: PATTED / RACING / HAPPILY rank low on the web
// but their bases (PAT, RACE, HAPPY) are common, so they're promoted. Frequency
// lists are web text, so names and junk leak through (GLORIA, FRANKLIN, ANON):
// data/wordlists/spellingbee-deny.txt removes them and spellingbee-allow.txt
// forces words in (one `WORD` or `WORD core` per line; the deny file takes any
// number of words per line). Both are hand-editable — edit, rerun.
//
// Usage: node tools/buildBeeWords.js [--freq path/to/count_1w.txt]
// [--suspects path/to/names.txt ...]
// --freq cached copy of https://norvig.com/ngrams/count_1w.txt (otherwise
// downloaded to the OS temp dir and cached there)
// --suspects print answer words that also appear in the given name lists and
// aren't yet in the deny/allow files — review them by hand.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const LISTS = path.join(__dirname, '../data/wordlists');
const ENABLE_PATH = path.join(LISTS, 'enable1.txt');
const DENY_PATH = path.join(LISTS, 'spellingbee-deny.txt');
const ALLOW_PATH = path.join(LISTS, 'spellingbee-allow.txt');
const OUT_PATH = path.join(LISTS, 'spellingbee-answers.txt');
const FREQ_URL = 'https://norvig.com/ngrams/count_1w.txt';
const A_CODE = 65;
const S_BIT = 1 << ('S'.charCodeAt(0) - A_CODE);
// Rank cutoffs (0-based rank in the Norvig list) by word length. Longer words
// are naturally rarer on the web, so their bar is looser. 4-letter words are
// where web junk concentrates (abbreviations, names), so they're strictest.
const CORE_CUTOFF = { 4: 20000, 5: 32000, 6: 42000, 7: 50000, default: 60000 };
const FAMILIAR_CUTOFF = { 4: 32000, 5: 60000, 6: 85000, 7: 95000, default: 100000 };
// A base word this common promotes its inflections (core base → familiar
// inflection; very common base → core inflection).
const BASE_CORE = 8000;
const BASE_FAMILIAR = 20000;
// …and the inflected form must still turn up on the web at least this often.
const PROMOTE_MAX_RANK = 200000;
const cut = (table, len) => table[len] ?? table.default;
// ── helpers ──────────────────────────────────────────────────────────────────
function argValues(flag) {
const out = [];
for (let i = 2; i < process.argv.length; i++) {
if (process.argv[i] === flag) {
for (let j = i + 1; j < process.argv.length && !process.argv[j].startsWith('--'); j++) out.push(process.argv[j]);
}
}
return out;
}
function wordMask(w) {
let m = 0;
for (let i = 0; i < w.length; i++) m |= 1 << (w.charCodeAt(i) - A_CODE);
return m;
}
function popcount(n) { let c = 0; while (n) { n &= n - 1; c++; } return c; }
// Bee-eligible: 4+ letters, A–Z only, no S, at most 7 distinct letters.
function beeEligible(w) {
if (w.length < 4 || !/^[A-Z]+$/.test(w)) return false;
const m = wordMask(w);
return !(m & S_BIT) && popcount(m) <= 7;
}
// Candidate base words for an inflected form (PATTED → PAT, RACING → RACE,
// HAPPILY → HAPPY, BIGGEST → BIG). Returns every plausible base; the caller
// keeps the most common one that exists.
function baseCandidates(w, enable) {
const out = [];
// No bare -Y (LINE → LINY) and no -ER agent nouns (HAY → HAYER, HONE → HONER):
// both are ENABLE-legal but mostly words nobody says.
const SUFFIXES = ['ING', 'ED', 'EST', 'LY', 'IER', 'IEST', 'ILY', 'NESS', 'FUL', 'MENT', 'ABLE'];
for (const suf of SUFFIXES) {
if (!w.endsWith(suf) || w.length - suf.length < 3) continue;
const stem = w.slice(0, -suf.length);
// A consonant-vowel-consonant stem would have doubled its last letter
// (LAD → LADDED), so when stem+E is a word the base is that (LADED → LADE,
// BARED → BARE), never the short stem.
if ((suf === 'ED' || suf === 'ING' || suf === 'EST') && /[^AEIOU][AEIOU][^AEIOUWXY]$/.test(stem)
&& enable.has(stem + 'E')) {
out.push(stem + 'E');
continue;
}
out.push(stem); // jumped → jump
out.push(stem + 'E'); // racing → race
if (suf.startsWith('I')) out.push(stem + 'Y'); // happier → happy
const n = stem.length;
if (n >= 3 && stem[n - 1] === stem[n - 2]) out.push(stem.slice(0, -1)); // patted → pat
}
return out;
}
function readList(file) {
if (!fs.existsSync(file)) return [];
return fs.readFileSync(file, 'utf8').split('\n')
.map((l) => l.replace(/#.*/, '').trim())
.filter(Boolean);
}
async function loadFreq() {
const given = argValues('--freq')[0];
if (given) return fs.readFileSync(given, 'utf8');
const cache = path.join(os.tmpdir(), 'count_1w.txt');
if (fs.existsSync(cache)) return fs.readFileSync(cache, 'utf8');
console.log('Downloading frequency list...');
const text = await (await fetch(FREQ_URL, { redirect: 'follow' })).text();
fs.writeFileSync(cache, text);
return text;
}
// ── main ─────────────────────────────────────────────────────────────────────
async function main() {
const enable = new Set(
fs.readFileSync(ENABLE_PATH, 'utf8').split('\n').map((w) => w.trim().toUpperCase()).filter(Boolean),
);
const rank = new Map();
(await loadFreq()).split('\n').forEach((line, i) => {
const w = line.split('\t')[0]?.toUpperCase();
if (w && /^[A-Z]+$/.test(w) && !rank.has(w)) rank.set(w, i);
});
const deny = new Set(readList(DENY_PATH).flatMap((l) => l.split(/\s+/)).map((w) => w.toUpperCase()));
const allow = new Map();
for (const l of readList(ALLOW_PATH)) {
const [w, tier] = l.split(/\s+/);
allow.set(w.toUpperCase(), tier === 'core' ? 'core' : 'familiar');
}
const tiers = new Map(); // word → 'core' | 'familiar'
for (const w of enable) {
if (!beeEligible(w) || deny.has(w)) continue;
const r = rank.get(w) ?? Infinity;
let tier = null;
if (r < cut(CORE_CUTOFF, w.length)) tier = 'core';
else if (r < cut(FAMILIAR_CUTOFF, w.length)) tier = 'familiar';
// Promotion needs the word itself to appear somewhere in the web list —
// an inflection nobody ever writes (COWY, DOGY) isn't familiar.
if (tier !== 'core' && r < PROMOTE_MAX_RANK) {
let best = Infinity;
for (const b of baseCandidates(w, enable)) {
if (b !== w && enable.has(b) && !deny.has(b)) best = Math.min(best, rank.get(b) ?? Infinity);
}
if (best < BASE_CORE && r < cut(FAMILIAR_CUTOFF, w.length) * 2) tier = 'core';
else if (best < BASE_FAMILIAR && !tier) tier = 'familiar';
}
if (tier) tiers.set(w, tier);
}
for (const [w, tier] of allow) {
if (!enable.has(w)) { console.warn(`allow: ${w} is not in ENABLE — skipped`); continue; }
if (!beeEligible(w)) { console.warn(`allow: ${w} can't appear in a hive (S / <4 / >7 letters) — skipped`); continue; }
tiers.set(w, tier);
}
const words = [...tiers.keys()].sort();
fs.writeFileSync(OUT_PATH, words.map((w) => `${w}\t${tiers.get(w)}`).join('\n') + '\n');
const counts = { core: 0, familiar: 0 };
for (const t of tiers.values()) counts[t]++;
console.log(`Wrote ${words.length} answer words to ${path.relative(process.cwd(), OUT_PATH)}`, counts);
const nameFiles = argValues('--suspects');
if (nameFiles.length) {
const names = new Set();
for (const f of nameFiles) {
for (const n of fs.readFileSync(f, 'utf8').split(/\r?\n/)) if (n.trim()) names.add(n.trim().toUpperCase());
}
const suspects = words.filter((w) => names.has(w) && !allow.has(w));
console.log(`\n${suspects.length} answer words also appear in the name lists (review → deny or allow):`);
console.log(suspects.map((w) => `${w}:${tiers.get(w)[0]}${rank.get(w) ?? '-'}`).join(' '));
}
}
main();