Created
December 23, 2017 18:43
-
-
Save twfarland/2004b8f419c9abb795381e7e579eab8b to your computer and use it in GitHub Desktop.
Crossword / Take 5 cheat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const readline = require('readline') | |
const fs = require('fs') | |
const lineReader = readline.createInterface({ | |
input: fs.createReadStream('/usr/share/dict/words', { encoding: 'utf8' }) | |
}) | |
const word = process.argv[2] | |
if (!word) { | |
console.log('Please give a word or pattern to check') | |
return | |
} | |
function allSame (xs) { | |
for (let i = 1; i < xs.length; i++) { | |
if (xs[i] !== xs[0]) { return false } | |
} | |
return true | |
} | |
function isCompletion (str, target) { | |
if (str.length !== target.length) { return false } // if not same length, can't be a match | |
const bound = {} | |
// Check each letter | |
for (let i = 0; i < str.length; i++) { | |
let c = str[i] | |
let c2 = target[i] | |
if (isNaN(c)) { // Is a letter or * | |
if (c === c2 || c === '*') { // Matches exactly or wildcard | |
continue | |
} else { | |
return false | |
} | |
} else { // Bind the number to the character | |
if (!bound[c]) { | |
bound[c] = [target[i]] | |
} else { | |
bound[c].push(target[i]) | |
} | |
} | |
} | |
// Ensure all chars at each binding are the same | |
for (let b in bound) { | |
if (!allSame(bound[b])) { | |
return false | |
} | |
} | |
return true | |
} | |
// Possible Words | |
// apple == apple | |
// ***** == apple | |
// a**** == apple | |
// a1123 == apple | |
// a1234 != apple | |
function test () { | |
console.log([ | |
isCompletion('eat', 'eat'), | |
isCompletion('***', 'eat'), | |
isCompletion('**', 'eat') === false, | |
isCompletion('****', 'eat') === false, | |
isCompletion('123', 'eat'), | |
isCompletion('122', 'too'), | |
isCompletion('e23', 'eat'), | |
isCompletion('111', 'eat') === false | |
]) | |
} | |
lineReader.on('line', line => { | |
if (isCompletion(word, line.toLowerCase().trim())) { | |
console.log(line) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment