Skip to content

Instantly share code, notes, and snippets.

@mvladic
Created March 4, 2022 16:07
Show Gist options
  • Select an option

  • Save mvladic/9b2f2025a8c54aca78649ce1776600b6 to your computer and use it in GitHub Desktop.

Select an option

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);
@albertdaurell
Copy link

https://gist.github.com/mvladic/9b2f2025a8c54aca78649ce1776600b6#file-solve-js-L15

-                    if (Number.isInteger(res)) {
+                    if (Number.isInteger(res) && res > 0) {

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