Last active
May 23, 2020 14:51
-
-
Save gkucmierz/60c25617f99164da16bd8cb779e54a53 to your computer and use it in GitHub Desktop.
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
const solveFor = (target, input, solveFn) => { | |
let solved = false; | |
const sort = arr => arr.sort((a, b) => a-b); | |
const nums = input.map(n => +n); | |
const ops = [...'+*']; | |
const fns = { | |
'+': (a, b) => a + b, | |
'*': (a, b) => a * b, | |
}; | |
const evalArr = arr => { | |
const el = arr.shift(); | |
if (el in fns) { | |
return fns[el](evalArr(arr), evalArr(arr)); | |
} | |
return el; | |
} | |
let cnt = 0; | |
const check = arr => { | |
++cnt; | |
const cpy = arr.slice(); | |
const res = evalArr(arr); | |
if (res !== target) return false; | |
solved = true; | |
solveFn(cpy); | |
}; | |
const genPermutations = size => { | |
const perms = []; | |
const gen = (res, used, shift) => { | |
if (used === size) { | |
perms.push(res); | |
} | |
for (let i = 0; i < (size-used); ++i) { | |
gen([...res, shift[i]], used + 1, [...shift.slice(0, i), ...shift.slice(i + 1)]); | |
} | |
}; | |
gen([], 0, new Array(size).fill(0).map((_, i) => i)); | |
return perms; | |
}; | |
const perms = genPermutations(nums.length) | |
const combinations = (res, perm) => { | |
if (solved) return true; | |
const target = perm.length * 2 - 1; | |
if (res.length >= target) { | |
return check(res); | |
} | |
for (let i = 0; i <= perm.length; ++i) { | |
for (let op of ops) { | |
const tmp = res.slice(); | |
tmp.splice(i, 0, op); | |
combinations(tmp, perm); | |
} | |
} | |
}; | |
perms.map(permIdx => { | |
const perm = permIdx.map(idx => nums[idx]); | |
combinations(perm, perm); | |
}); | |
}; | |
` | |
9 2 4 3 1 | |
11 1 2 3 4 | |
13 1 2 3 4 | |
17 1 2 3 4 | |
18 1 2 3 4 | |
21 1 2 3 4 | |
19 1 2 3 4 | |
36 1 2 3 4 | |
30 1 2 3 4 | |
32 1 2 3 3 4 | |
24 2 2 4 4 | |
24 2 2 2 9 | |
24 1 2 2 9 | |
24 2 2 4 7 | |
24 1 5 7 11 | |
24 2 2 3 3 | |
24 1 2 6 6 | |
24 2 3 3 3 | |
24 3 3 3 4 | |
`.split(/\n/g).filter(s => s !== '').map(expr => { | |
const [target, ...input] = expr.split(/\s/).map(n => +n); | |
solveFor(target, input, solution => { | |
console.log(target, ' => ', solution.join` `); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment