Skip to content

Instantly share code, notes, and snippets.

@YanivHaramati
Last active October 18, 2016 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YanivHaramati/884b77776d207ce0f13f6b327431d6e7 to your computer and use it in GitHub Desktop.
Save YanivHaramati/884b77776d207ce0f13f6b327431d6e7 to your computer and use it in GitHub Desktop.
Map a phone number to potential words. This part produces all possible combinations.
var digits = {2: ['a', 'b', 'c'], 3: ['d', 'e', 'f'], 4: ['g','h','i'], 5: ['j','k','l'], 6: ['m','n','o'], 7:['p', 'q', 'r', 's'], 8: ['t','u','v'], 9: ['x','y','z']};
function crossProduct(sets) {
var r = sets.reduce((p,c) => {
return p.map(x => {
return c.map(y => {
return x.concat(y);
})
}).reduce((prev,cur) => { return prev.concat(cur) },[])
}, [[]]).map(s => s.join(''));
return r;
}
function getSets(number) {
return number.split('').map(n => (digits[n]) ? digits[n] : [])
.filter(s => s.length);
}
module.exports = {
getCombos: number => {
var sets = getSets(number);
return crossProduct(sets);
}
};
// usage: node numberAnalyzer.js 4243
// output: [ 'gage', 'ibid' ]
var digitConverter = require('./combos');
var natural = require("natural");
var fs = require("fs");
// assumes that you have a '\n'-separated english dictionary file.
// which you can get from a number of places...
const dictionary = "dictionary/en_wordlist.txt";
const number = process.argv[2];
var trie = new natural.Trie(false);
var loadDictionary = new Promise((resolve, reject) => {
fs.readFile(dictionary, {"encoding":"ascii"}, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
loadDictionary.then(data => {
var words = data.split("\n").map(w => w.trim())
.filter(w => w.length <= 10);
trie.addStrings(words);
var combos = digitConverter.getCombos(number);
var words = combos.filter(w => trie.contains(w));
if (words.length) {
console.log(words);
} else {
console.log('no matches.');
}
}).catch(err => {
console.err(err);
});
@YanivHaramati
Copy link
Author

YanivHaramati commented Oct 17, 2016

node numberAnalyzer.js 3878
[ 'dust' ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment