Skip to content

Instantly share code, notes, and snippets.

@jpbochi
Last active January 2, 2016 06:29
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 jpbochi/8264247 to your computer and use it in GitHub Desktop.
Save jpbochi/8264247 to your computer and use it in GitHub Desktop.
hats
//http://repl.it/IOn
function problem(colors, prisoners) {
function randomHat() {
return Math.floor(Math.random() * colors);
}
function randomHats() {
var hats = [];
for (var i = 0; i<prisoners; i++) {
hats.push(randomHat());
}
return hats;
}
function zip() {
var arrays = [].slice.call(arguments);
return arrays[0].map(function(_,i){
return arrays.map(function(array){return array[i]});
});
}
function play(strategy, hats, log) {
hats = hats || randomHats();
log = log || console.log;
var guesses = [];
var hatsRemaining = hats.slice(0);
log && log('----- problem -----');
log && log('colors =', colors);
log && log('strategy =', strategy.name);
log && log('hats =', hats.join('|'));
while (hatsRemaining.length > 0) {
var hat = hatsRemaining.shift();
//log && log('----- round #' + guesses.length + ' -----');
//log && log('behind =', guesses, 'hat =', hat, 'ahead =', hatsRemaining);
guesses.push(strategy(guesses, hatsRemaining, colors));
//log && log('guess =', guesses.slice(-1)[0]);
}
var deaths = zip(hats, guesses).map(function (pair) {
return pair[0] === pair[1] ? '.' : 'X';
});
var survivors = deaths.reduce(function(total, death) {
return death === '.' ? total + 1 : total;
}, 0);
log && log('----- result -----');
log && log('guesses =', guesses.join('|'));
log && log('deaths =', deaths.join(''));
log && log('survivors =', survivors);
log && log('----- end -----');
return survivors;
}
return {
randomHat: randomHat,
randomHats: randomHats,
play: play
};
}
function random(guesses, ahead, colors) {
return problem(colors).randomHat();
}
function smart(guesses, ahead, colors) {
function sum(hats) {
return hats.reduce(function (sum, hat) {
return sum + hat;
}, 0);
}
if (guesses.length === 0) {
return sum(guesses.concat(ahead)) % colors;
}
var first = guesses[0];
var everyoneElse = guesses.slice(1).concat(ahead);
var everyoneElseSum = sum(everyoneElse) % colors;
var guess = (first - everyoneElseSum + colors) % colors;
return guess;
}
problem(3, 10).play(smart);
//other examples:
//problem(3, 20).play(random);
//problem(6, 100).play(smart);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment