Created
March 20, 2014 16:04
-
-
Save poppycocker/9667255 to your computer and use it in GitHub Desktop.
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
// Poison Wine | |
// http://blog.livedoor.jp/kinisoku/archives/4023190.html | |
(function() { | |
var WINE_COUNT = 1000; | |
// Phase0: Preparing | |
var poisonousWineIdx = Math.floor(Math.random() * (WINE_COUNT + 1)); | |
var slaveNum = Math.floor((Math.log(WINE_COUNT) / Math.log(2)) + 1); | |
var slaves = []; | |
var i = 0, j = 0; | |
for (; i < slaveNum; i++) { | |
slaves.push(false); | |
} | |
// Phase1: Tasting | |
// The poison is slow-acting, | |
// so slaves must drink all wine to identify the poisonous one. | |
for (i = 1; i <= WINE_COUNT; i++) { | |
for (j = 0; j < slaveNum; j++) { | |
if (!!((i >> (slaveNum - j - 1)) & 1)) { | |
// current slave drinks this wine. | |
slaves[j] |= (i === poisonousWineIdx); | |
} | |
} | |
} | |
// Phase2: Get Solution | |
var answer = parseInt(slaves.join(''), 2); | |
// Show Result | |
console.log(poisonousWineIdx + ', ' + answer); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment