Created
December 26, 2020 11:24
-
-
Save gko/5ec9be1fc0f9c5b7593309f4a4d91120 to your computer and use it in GitHub Desktop.
isAnagram via product of prime numbers https://twitter.com/fermatslibrary/status/875340896379817984/photo/1
This file contains hidden or 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
// https://twitter.com/fermatslibrary/status/875340896379817984/photo/1 | |
const memoizedWords: { | |
[Key: string]: number; | |
} = {}; | |
const ALPHABET_MAPPED_TO_PRIME_NUMBERS: { | |
[Key: string]: number; | |
} = { | |
a: 2, | |
b: 3, | |
c: 5, | |
d: 7, | |
e: 11, | |
f: 13, | |
g: 17, | |
h: 19, | |
i: 23, | |
j: 29, | |
k: 31, | |
l: 37, | |
m: 41, | |
n: 43, | |
o: 47, | |
p: 53, | |
q: 59, | |
r: 61, | |
s: 67, | |
t: 71, | |
u: 73, | |
v: 79, | |
w: 83, | |
x: 89, | |
y: 97, | |
z: 101, | |
}; | |
const wordProduct = (word: string) => { | |
const lowerCaseWord: string = word.toLowerCase(); | |
return ( | |
memoizedWords[lowerCaseWord] || | |
((memoizedWords[lowerCaseWord] = lowerCaseWord | |
.split("") | |
.reduce( | |
(acc, letter) => acc * ALPHABET_MAPPED_TO_PRIME_NUMBERS[letter], | |
1 | |
)), | |
memoizedWords[lowerCaseWord]) | |
); | |
}; | |
const isAnagram = (wordA: string, wordB: string) => { | |
if (wordB === wordA) return false; | |
return wordProduct(wordA) === wordProduct(wordB); | |
}; | |
export { isAnagram }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment