Last active
May 4, 2020 03:24
-
-
Save gkucmierz/81f9a5bb8c17a33a3b899888b7864b79 to your computer and use it in GitHub Desktop.
alphametic puzzle solver (brute force)
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
// alphametic puzzle solver (brute force) | |
const solve = (a, b, c, s) => { | |
const uniq = [...new Set([...(a+b+c+s)])]; | |
const res = []; | |
const rec = nums => { | |
if (nums.length >= uniq.length) { | |
const an = +[...a].map(l => nums[uniq.indexOf(l)]).join``; | |
const bn = +[...b].map(l => nums[uniq.indexOf(l)]).join``; | |
const cn = +[...c].map(l => nums[uniq.indexOf(l)]).join``; | |
const sn = +[...s].map(l => nums[uniq.indexOf(l)]).join``; | |
if (an + bn +cn === sn) { | |
res.push(nums); | |
} | |
return; | |
} | |
for (let i = 0; i < 10; ++i) { | |
if (!nums.includes(i)) { | |
rec([...nums, i]); | |
} | |
} | |
}; | |
rec([]); | |
res.map(nums => { | |
const an = +[...a].map(l => nums[uniq.indexOf(l)]).join``; | |
const bn = +[...b].map(l => nums[uniq.indexOf(l)]).join``; | |
const cn = +[...c].map(l => nums[uniq.indexOf(l)]).join``; | |
const sn = +[...s].map(l => nums[uniq.indexOf(l)]).join``; | |
console.log(`${an} + ${bn} + ${cn} = ${sn}`); | |
}); | |
}; | |
solve('aaa', 'bbb', 'ccc', 'baac'); | |
solve('', 'send', 'more', 'money'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment