Word store matching ? wildcard patterns with counts
A crossword helper lets players type a partly known answer such as c?t, where each ? is a square they have not filled in yet. It tells them whether any word fits, and how many candidates there are. Players can also add their own words and remove ones they never want suggested.
Implement a WordLexicon class.
const lexicon = new WordLexicon();
lexicon.add(word); // => true if the word is new, false if it was already stored
lexicon.remove(word); // => true if the word was stored and is now removed, else false
lexicon.has(pattern); // => true if at least one stored word matches
lexicon.count(pattern); // => number of stored words that match
a–z. A word is stored at most once.? matches exactly one letter. Every other character matches only itself. A word matches only if it has the same length as the pattern, so 'ca' does not match 'cat' and 'c?' does not match 'cat'.add and remove take plain words, never patterns.remove removes one whole word. Removing 'car' keeps 'cart', and removing a prefix that was never added ('ca') returns false.const lexicon = new WordLexicon();
['cat', 'cot', 'cut', 'cart', 'coat'].forEach((word) => lexicon.add(word));
lexicon.add('cat'); // => false (already stored)
lexicon.has('c?t'); // => true
lexicon.count('c?t'); // => 3 (cat, cot, cut)
lexicon.count('c??t'); // => 2 (cart, coat)
lexicon.count('????'); // => 2
lexicon.has('c?'); // => false (length must match)
lexicon.has('ca'); // => false (a prefix is not a word)
lexicon.remove('cot'); // => true
lexicon.remove('cot'); // => false
lexicon.count('c?t'); // => 2
lexicon.remove('co'); // => false
lexicon.has('coat'); // => true
A trie (prefix tree) is the natural structure: a literal letter follows one branch, and ? explores every branch at that depth.