Skip to content

Instantly share code, notes, and snippets.

@johnislarry
Created November 10, 2016 22:25
Show Gist options
  • Save johnislarry/f974522d764f0f495f51f584955f6369 to your computer and use it in GitHub Desktop.
Save johnislarry/f974522d764f0f495f51f584955f6369 to your computer and use it in GitHub Desktop.
'use strict';
function swiftney_impl(nums, expr, goal) {
if (goal === eval(expr) && nums.length === 0) {
console.log(`${expr} = ${goal}`);
}
if (nums.length > 0) {
const num = nums[0];
['+', '-', '*', '/'].forEach(op => swiftney_impl(nums.slice(1), `(${expr}${op}${num})`, goal));
}
}
function swiftney(nums, goal) {
const num = nums[0];
swiftney_impl(nums.slice(1), `${num}`, goal);
}
function permutations_impl(xs, res, acc) {
if (xs.length === 0) {
acc.push(res);
return acc;
}
for (let i = 0; i < xs.length; i++) {
const newres = res.slice();
newres.push(xs[i]);
permutations_impl(xs.slice(0, i).concat(xs.slice(i+1, xs.length)), newres, acc);
}
return acc;
}
function permutations(xs) {
return permutations_impl(xs, [], []);
}
const nums = [1,7,7,2,3,2];
const goal = 131;
for (const p of permutations(nums)) {
swiftney(p, goal);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment