Created
October 9, 2020 13:31
-
-
Save EXayer/58918d30ab0a20161468a0d2176efa20 to your computer and use it in GitHub Desktop.
The Monty Hall Problem - brute force proof
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
const CHANCE = 3; | |
function rollDoor() { | |
return Math.floor(Math.random() * CHANCE); | |
} | |
function randArr(arr) { | |
return arr[Math.floor(Math.random() * arr.length)]; | |
} | |
function removeRandom(arr, hidden, choosen) { | |
if (hidden !== choosen) { | |
return [arr[hidden], arr[choosen]]; | |
} | |
const variants = []; | |
for (let i = 0; i < arr.length; i++) { | |
if (hidden === i || choosen === i) { | |
continue; | |
} | |
variants.push(arr[i]); | |
} | |
return [arr[hidden], randArr(variants)]; | |
} | |
function game(do_choose = false, times = 100000) { | |
const stat = { | |
'count': times, | |
'win': 0, | |
'lose': 0 | |
}; | |
for (let i = 0; i < times; i++) { | |
const variants = [1, 2, 3]; | |
const hidden = rollDoor(); | |
const choosen = rollDoor(); | |
// remove 1 door | |
const variants2 = removeRandom(variants, hidden, choosen); | |
if (do_choose) { | |
let new_choosen = -1; | |
for (let i = 0; i <= variants2.length; i++) { | |
if (variants[choosen] !== variants2[i]) { | |
new_choosen = variants2[i]; | |
break; | |
} | |
} | |
if (variants[hidden] === new_choosen) { | |
stat['win']++; | |
} else { | |
stat['lose']++; | |
} | |
continue; | |
} | |
if (choosen === hidden) { | |
stat['win']++; | |
} else { | |
stat['lose']++; | |
} | |
} | |
return stat; | |
} | |
const stat = game(); | |
console.log('------ No Change -------'); | |
console.log(`Count: ${stat['count']}, Win: ${stat['win']}, Lose: ${stat['lose']}`); | |
const stat2 = game(true); | |
console.log('------- New Door -------'); | |
console.log(`Count: ${stat2['count']}, Win: ${stat2['win']}, Lose: ${stat2['lose']}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment