1000本のワインの中から1本の毒入りワインを見つける問題を解いた
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
/* 一滴でも飲むと20時間後に死ぬ毒が、1000本のワインのうち1本にだけ入っている。 奴隷に飲ませて、24時間以内にどれが毒入りか調べるとき、奴隷は何人必要か。 こたえ 10人。 検出アルゴリズムのテスト。 */ class Wine { constructor(id, isPoison) { this.id = id; this.isPoison = isPoison; } pour() { return this.isPoison; } } class Slave { constructor(pos) { this.pos = pos; this.poisoned = false; } drink(wine){ this.isPoisoned = (this.isPoisoned || wine.pour()); } } const p = console.log; function readSlaves(slaves) { const len = slaves.length; let s = ''; for(let i=len-1; 0<=i; i--){ const slave = slaves[i]; s += (slave.isPoisoned ? '1' : '0'); } return s; } function decimalToBinaryStrPadded(n) { return ('0000000000' + n.toString(2)).substr(-10); } function binaryDrinking(slaves, wines) { wines.forEach(wine => { const binStrPadded = decimalToBinaryStrPadded(wine.id); slaves.forEach(slave => { if(binStrPadded.substr(9 - slave.pos, 1) === '1'){ slave.drink(wine); } }); }); } function setWinePoison(wines, id) { wines.forEach(wine => { if(wine.id === id){ wine.isPoison = true; return; } }); } function binKetaToNum(binKeta) { if(binKeta < 0) { return 0; } return Math.pow(2, binKeta); } function binStrToDecimal(s) { const len = s.length; let sum = 0; for(let i=len-1; 0<=i; i--){ const binKeta = len-1-i; const on = (s.substr(i, 1) === '1'); if(on){ sum += binKetaToNum(binKeta); } } return sum; } function generateSlaves() { const slaves = []; for(let i=0; i<10; i++) { slaves.push(new Slave(i)); } return slaves; } function generateWines() { const wines = []; for(let i=0; i<1000; i++){ wines.push(new Wine(i+1, false)); } return wines; } function tasting(poisonWineId){ const slaves = generateSlaves(); const wines = generateWines(); setWinePoison(wines, poisonWineId); binaryDrinking(slaves, wines); const binaryStr = readSlaves(slaves); p( "poisonWineId : " + poisonWineId + ", " + "readSlaves(slaves) : " + binaryStr ); } function main() { tasting(0); tasting(777); tasting(1000); } main(); |
1 2 3 |
poisonWineId : 0, readSlaves(slaves) : 0000000000 poisonWineId : 777, readSlaves(slaves) : 1100001001 poisonWineId : 1000, readSlaves(slaves) : 1111101000 |