Created
December 16, 2021 15:29
-
-
Save gillchristian/a520a0ebedee19ed429e45e9d4578d97 to your computer and use it in GitHub Desktop.
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 fs = require("fs"); | |
const letterToNumber = { | |
a: 2, | |
b: 2, | |
c: 2, | |
d: 3, | |
e: 3, | |
f: 3, | |
g: 4, | |
h: 4, | |
i: 4, | |
j: 5, | |
k: 5, | |
l: 5, | |
m: 6, | |
n: 6, | |
o: 6, | |
p: 7, | |
q: 7, | |
r: 7, | |
s: 7, | |
t: 8, | |
u: 8, | |
v: 8, | |
w: 9, | |
x: 9, | |
y: 9, | |
z: 9, | |
}; | |
const numberToLetters = { | |
2: "abc".split(""), | |
3: "def".split(""), | |
4: "ghi".split(""), | |
5: "jkl".split(""), | |
6: "mno".split(""), | |
7: "pqrs".split(""), | |
8: "tuv".split(""), | |
9: "wxyz".split(""), | |
}; | |
const wordToNumber = (word) => | |
word | |
.toLowerCase() | |
.split("") | |
.map((l) => `${letterToNumber[l]}`) | |
.join(""); | |
const wordToNumber_ = (word) => | |
word | |
.toLowerCase() | |
.split("") | |
.reduce((acc, l) => `${acc}${letterToNumber[l]}`, ""); | |
console.log("--- Word to number ----\n"); | |
console.log(wordToNumber("adeg")); | |
console.log(wordToNumber_("adeg")); | |
console.log(); | |
// ----------------------------------------------------------------------------- | |
console.log("--- Number to words ---\n"); | |
// O(n) | |
const englishWords = new Set( | |
fs | |
// Mac OS | |
.readFileSync("/usr/share/dict/words", "utf8") | |
.split("\n") | |
.map((word) => word.toLowerCase()) | |
); | |
console.log("ENGLISH WORDS COUNT:", englishWords.size); | |
console.log(); | |
const flatten = (xss) => [].concat(...xss); | |
// O(n * m) | |
const allPairsWith = (f) => (as, bs) => | |
flatten(as.map((a) => bs.map((b) => f(a, b)))); | |
const append = (a, b) => `${a}${b}`; | |
const numberToWords = (num) => { | |
// Array.map -> O(n) | |
// String.split -> O(n) | |
const letters = num.split("").map((n) => numberToLetters[n]); | |
const combinations = letters | |
.slice(1) | |
.reduce((acc, ls) => allPairsWith(append)(acc, ls), letters[0] || []); | |
return combinations; | |
}; | |
console.log({ | |
23: numberToWords("23").length, | |
234: numberToWords("234").length, | |
237: numberToWords("237").length, | |
9987: numberToWords("9987").length, | |
}); | |
const numberToValidWords = (words) => | |
// Array.filter -> O(n) | |
// Set.has -> O(1) | |
words.filter((word) => englishWords.has(word)); | |
console.log(numberToValidWords(numberToWords("23"))); | |
console.time("Holland"); | |
const holland = wordToNumber_("Holland"); | |
console.log("Holland: ->", holland); | |
console.log(holland, "->", numberToValidWords(numberToWords(holland))); | |
console.timeEnd("Holland"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment