Created
March 4, 2022 16:07
-
-
Save mvladic/9b2f2025a8c54aca78649ce1776600b6 to your computer and use it in GitHub Desktop.
Summle solver (https://summle.net/)
This file contains 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
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); |
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
Output: