初版は間違えてた。はづかしい
モンティホール問題
「プレーヤーの前に閉まった3つのドアがあって、1つのドアの後ろには景品の新車が、2つのドアの後ろには、はずれを意味するヤギがいる。プレーヤーは新車のドアを当てると新車がもらえる。プレーヤーが1つのドアを選択した後、司会のモンティが残りのドアのうちヤギがいるドアを開けてヤギを見せる。ここでプレーヤーは、最初に選んだドアを、残っている開けられていないドアに変更してもよいと言われる。プレーヤーはドアを変更すべきだろうか?」
変更しない場合の正解の確率は 1/3, 変更した場合の正解の確率は 2/3。よって変更した方がよい。
コード
30000 回の試行をして、変更しない場合は 10000回程度の成功、 変更する場合は20000 回程度の成功となることを確かめる。
const BOX = [0, 1, 2];
const randInt = num => Math.floor(Math.random() * num);
const chooseRandomFrom = arr => arr[randInt(arr.length)];
const playWithoutRechoice = (answer, choice) => choice === answer;
const playWithRechoice = (answer, choice) => {
const opened = chooseRandomFrom(BOX.filter(x => x !== answer && x !== choice));
const rechoice = chooseRandomFrom(BOX.filter(x => x !== choice && x !== opened));
return rechoice === answer;
};
// main
const count = { without: 0, rechoice: 0 };
for (let i = 0; i < 30000; i += 1) {
const [answer, choice] = [chooseRandomFrom(BOX), chooseRandomFrom(BOX)];
if (playWithoutRechoice(answer, choice)) count.without += 1;
if (playWithRechoice(answer, choice)) count.rechoice += 1;
}
console.log(count);
結果。いい感じ。
{ without: 10054, rechoice: 19946 }