Skip to content

Instantly share code, notes, and snippets.

@tkihira
Created April 1, 2013 11:27
Show Gist options
  • Save tkihira/5284435 to your computer and use it in GitHub Desktop.
Save tkihira/5284435 to your computer and use it in GitHub Desktop.
var check = function(digits) {
var make_equations = function(digits, strict) {
var numbers = digits.length;
var equations = {};
var current = [];
var make_recursive = function(num_list, nums, operations) {
if(num_list.length == 0 && operations == 0) {
equations[current.join("")] = true;
return;
}
if(num_list.length) {
for(var i = 0; i < (strict? 1: num_list.length); i++) {
var list = [].concat(num_list);
list.splice(i, 1);
current.push(num_list[i]);
make_recursive(list, nums + 1, operations);
current.pop();
}
}
if(nums >= 2) {
for(var i = 0; i < 4; i++) {
current.push(["+", "-", "*", "/"][i]);
make_recursive(num_list, nums - 1, operations - 1);
current.pop();
}
}
};
make_recursive(digits, 0, numbers - 1);
return Object.keys(equations);
};
var solve = function(eq) {
var stack = [];
eq.split("").forEach(function(d) {
switch(d) {
case '+': stack.push(stack.pop() + stack.pop()); break;
case '-': stack.push(-stack.pop() + stack.pop()); break;
case '*': stack.push(stack.pop() * stack.pop()); break;
case '/': stack.push(1 / stack.pop() * stack.pop()); break;
default: stack.push(d - 0); break;
}
});
return Math.abs(stack[0] - 10) < 0.0001;
};
var solve_list = [];
make_equations(digits).forEach(function(eq) {
if(solve(eq)) {
solve_list.push(eq);
}
});
return solve_list;
};
//var puzzle = "1158";
//var digits = puzzle.split("").map(function(s) { return s - 0; });
var solves = [];
var list = [];
var count = 0;
var start_time = Date.now();
var make_digit = function(current, len) {
if(len == 0) {
count++;
if(count % 20 == 0) {
console.log(count + "/2002 done(" + (Date.now() - start_time) / 1000 + "s)");
}
var s = check(list);
if(s.length) {
solves.push({solve: s, problem: list.join("")});
}
return;
}
for(var i = current; i <= 9; i++) {
list.push(i);
make_digit(i, len - 1);
list.pop();
}
};
make_digit(0, 5);
solves.sort(function(a, b) {
return b.solve.length - a.solve.length;
});
solves.forEach(function(e) {
console.log(e.problem + ":" + e.solve.length + ":" + e.solve[0]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment