Skip to content

Instantly share code, notes, and snippets.

@migerh
Created February 6, 2011 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save migerh/813292 to your computer and use it in GitHub Desktop.
Save migerh/813292 to your computer and use it in GitHub Desktop.
Solve the equation "1 2 3 4 5 6 7 8 9 = 100" by putting in only adds and takes. Requires a div with id "result" on the page to work.
var calc = function() {
var coefficients = [1, 2, 3, 4, 5, 6, 7, 8, 9],
signTable = ['-', '', '+'],
cases = 0,
caseFormula = '',
ternary = '',
i = 0,
result = {},
r = document.getElementById('result'),
toTernary = function(n) {
var s = '', b = 3;
n = parseInt(n, 10);
while(n >= b) {
s = (n % b) + s;
n = Math.floor(n/b);
}
return ((n != 0 ? n : '') + s);
},
pad = function(s) {
var i, add = coefficients.length - s.length;
for(i = 0; i < add; i++) {
s = '0' + s;
}
return s;
},
evaluate = function(s) {
var sign = 1, values = [], i, result = 0;
for(i = 0; i < s.length; i++) {
switch(s[i]) {
case '+':
result += sign*values.join('');
sign = 1;
values = [];
break;
case '-':
result += sign*values.join('');
sign = -1;
values = [];
break;
default:
values.push(s[i]);
}
}
return result + sign*values.join('');
};
for(cases = 0; cases < 19683; cases++) {
caseFormula = '';
ternary = pad(toTernary(cases));
for(i = 0; i < coefficients.length; i++) {
caseFormula += signTable[parseInt(ternary[coefficients.length-i-1])] + coefficients[i];
}
if(100 == evaluate(caseFormula)) {
result[caseFormula] = 0;
}
}
cases = 0;
for(i in result) {
if(100 == eval(i)) {
r.innerHTML += i + ' = 100<br /' + '>';
cases++;
}
}
r.innerHTML += '<br /' + '>Found ' + cases + ' solutions.';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment