This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,38 @@
function montyhall(tests, doors) {
'use strict';
tests = tests ? tests : 1000;
doors = doors ? doors : 3;
var prizeDoor, chosenDoor, shownDoor, switchDoor, chosenWins = 0, switchWins = 0;
// randomly pick a door excluding input doors
function pick(excludeA, excludeB) {
var door;
do {
door = Math.floor(Math.random() * doors);
} while (door === excludeA || door === excludeB);
return door;
}
// run tests
for (var i = 0; i < tests; i ++) {
// pick set of doors
prizeDoor = pick();
chosenDoor = pick();
shownDoor = pick(prizeDoor, chosenDoor);
switchDoor = pick(chosenDoor, shownDoor);
// test set for both choices
if (chosenDoor === prizeDoor) {
chosenWins ++;
} else if (switchDoor === prizeDoor) {
switchWins ++;
}
}
// results
return {
stayWins: chosenWins + ' ' + (100 * chosenWins / tests) + '%',
switchWins: switchWins + ' ' + (100 * switchWins / tests) + '%'
};
}

View file

@ -0,0 +1,6 @@
montyhall(1000, 3)
Object {stayWins: "349 34.9%", switchWins: "651 65.1%"}
montyhall(1000, 4)
Object {stayWins: "253 25.3%", switchWins: "384 38.4%"}
montyhall(1000, 5)
Object {stayWins: "202 20.2%", switchWins: "265 26.5%"}

View file

@ -0,0 +1,44 @@
var totalGames = 10000,
selectDoor = function () {
return Math.floor(Math.random() * 3); // Choose a number from 0, 1 and 2.
},
games = (function () {
var i = 0, games = [];
for (; i < totalGames; ++i) {
games.push(selectDoor()); // Pick a door which will hide the prize.
}
return games;
}()),
play = function (switchDoor) {
var i = 0, j = games.length, winningDoor, randomGuess, totalTimesWon = 0;
for (; i < j; ++i) {
winningDoor = games[i];
randomGuess = selectDoor();
if ((randomGuess === winningDoor && !switchDoor) ||
(randomGuess !== winningDoor && switchDoor))
{
/*
* If I initially guessed the winning door and didn't switch,
* or if I initially guessed a losing door but then switched,
* I've won.
*
* The only time I lose is when I initially guess the winning door
* and then switch.
*/
totalTimesWon++;
}
}
return totalTimesWon;
};
/*
* Start the simulation
*/
console.log("Playing " + totalGames + " games");
console.log("Wins when not switching door", play(false));
console.log("Wins when switching door", play(true));

View file

@ -0,0 +1,3 @@
Playing 10000 games
Wins when not switching door 3326
Wins when switching door 6630