Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Last active May 4, 2020 03:24
Show Gist options
  • Save gkucmierz/81f9a5bb8c17a33a3b899888b7864b79 to your computer and use it in GitHub Desktop.
Save gkucmierz/81f9a5bb8c17a33a3b899888b7864b79 to your computer and use it in GitHub Desktop.
alphametic puzzle solver (brute force)
// 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