Created
February 6, 2011 11:02
-
-
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.
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
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