Skip to content

Instantly share code, notes, and snippets.

@nknapp
Last active August 29, 2015 14:14
Show Gist options
  • Save nknapp/23276b87eaba9f8afacd to your computer and use it in GitHub Desktop.
Save nknapp/23276b87eaba9f8afacd to your computer and use it in GitHub Desktop.
// Let a,b and c be 3-digit numbers such that every digit 1 to 9
// occurs exactly once if all number are written in concatenation.
// For which number is a+b=c true.
// This is a riddle from a mathematics-book for fourth-graders. It is marked
// as "difficult, for students that are faster than others".
var buffer = [0,0,0,0,0,0,0,0,0];
function add(pos, callback) {
if (pos<0) {
callback(buffer);
return;
}
for(var i=1; i<=9;i++) {
if (buffer.indexOf(i,pos)<0) {
buffer[pos]=i;
add(pos-1,callback);
}
}
}
add(8,function(permutation) {
var a = permutation[0]*100 + permutation[1]*10 + permutation[2];
var b = permutation[3]*100 + permutation[4]*10 + permutation[5];
var c = permutation[6]*100 + permutation[7]*10 + permutation[8];
if (a+b==c) {
console.log(a+" + "+b+" = "+c);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment