Skip to content

Instantly share code, notes, and snippets.

@mvladic
Created March 4, 2022 16:07
Show Gist options
  • Save mvladic/9b2f2025a8c54aca78649ce1776600b6 to your computer and use it in GitHub Desktop.
Save mvladic/9b2f2025a8c54aca78649ce1776600b6 to your computer and use it in GitHub Desktop.
Summle solver (https://summle.net/)
const target = 486;
const nums = [3, 3, 6, 8, 9, 100];
const op = [['+', (a, b) => a + b], ['-', (a, b) => a - b], ['*', (a, b) => a * b], ['/', (a, b) => a / b]];
let numSolutions = 0;
let bestSolution;
function solve(nums, solution) {
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (j != i) {
for (let k = 0; k < op.length; k++) {
const res = op[k][1](nums[i], nums[j]);
if (Number.isInteger(res)) {
const newSolution = [...solution, `${nums[i]} ${op[k][0]} ${nums[j]} = ${res}`];
if (res == target) {
numSolutions++;
if (!bestSolution || newSolution.length < bestSolution.length) {
bestSolution = newSolution;
console.log(newSolution);
}
} else {
if (newSolution.length < 5) {
const newNums = nums.slice();
newNums.splice(i, 1);
newNums.splice(j - (i < j ? 1 : 0), 1);
newNums.push(res);
solve(newNums, newSolution);
}
}
}
}
}
}
}
}
solve(nums, []);
console.log(numSolutions);
@mvladic
Copy link
Author

mvladic commented Mar 4, 2022

Output:

❯ node solve.js
[ '3 + 3 = 6', '6 * 8 = 48', '6 + 48 = 54', '9 * 54 = 486' ]
[ '3 * 3 = 9', '6 * 9 = 54', '9 * 54 = 486' ]
6368

@kenwilcox
Copy link

Interesting. Thanks for this solver. wouldn't the "best" be [ '3 * 3 = 9', '9 * 6 = 54', '9 * 54 = 486' ] though, right? only 3 "moves"
2022-03-04 (1)
?

@mvladic
Copy link
Author

mvladic commented Mar 5, 2022

Program prints first solution it finds, then if it finds better solution, with less steps, it prints that also, etc. So, in output there is one solution with 4 steps, and one with 3 steps - similar to yours.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment