Skip to content

Instantly share code, notes, and snippets.

@tonyonodi
Created April 23, 2018 15:29
Show Gist options
  • Save tonyonodi/c0aaf77a7a4d886f8a3c028226d4577b to your computer and use it in GitHub Desktop.
Save tonyonodi/c0aaf77a7a4d886f8a3c028226d4577b to your computer and use it in GitHub Desktop.
Find anagrams using the fundamental theorem of arithmetic.
// Find anagrams using the fundamental theorem of arithmetic. Not at all
// efficient and stops working very quickly due to floating point imprecision.
// Inspired by https://twitter.com/fermatslibrary/status/988399621402656773
const primes = {
"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 getPrimeProduct = s => s
.toLowerCase()
.replace(/\s/g, "")
.split("")
.map(c => primes[c])
.reduce((val, acc) => val * acc);
const isAnagram = (a, b) => getPrimeProduct(a) === getPrimeProduct(b);
console.log(isAnagram("are", "ear"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment