Monty Hall problem: Difference between revisions

Content added Content deleted
Line 1,598: Line 1,598:


=={{header|JavaScript}}==
=={{header|JavaScript}}==

===Extensive Solution===

This solution can test with n doors, the difference in probability of switching is shown to diminish as the number of doors increases.

<lang javascript>
function montyhall(tests, doors) {
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 + ' / ' + tests + ' ' + (100 * chosenWins / tests) + '%',
switchWins: switchWins + ' / ' + tests + ' ' + (100 * switchWins / tests) + '%'
}
}
</lang>

Output:

<lang javascript>
montyhall(1000, 3)
Object {stayWins: "349 / 1000 34.9%", switchWins: "651 / 1000 65.1%"}
montyhall(1000, 4)
Object {stayWins: "247 / 1000 24.7%", switchWins: "351 / 1000 35.1%"}
montyhall(1000, 5)
Object {stayWins: "205 / 1000 20.5%", switchWins: "268 / 1000 26.8%"}
</lang>

===Basic Solution===

{{output?|JavaScript}}
{{output?|JavaScript}}
<!-- http://blog.dreasgrech.com/2011/09/simulating-monty-hall-problem.html -->
<!-- http://blog.dreasgrech.com/2011/09/simulating-monty-hall-problem.html -->
<lang javascript>var totalGames = 10000,
<lang javascript>
var totalGames = 10000,
selectDoor = function () {
selectDoor = function () {
return Math.floor(Math.random() * 3); // Choose a number from 0, 1 and 2.
return Math.floor(Math.random() * 3); // Choose a number from 0, 1 and 2.
Line 1,643: Line 1,702:
console.log("Playing " + totalGames + " games");
console.log("Playing " + totalGames + " games");
console.log("Wins when not switching door", play(false));
console.log("Wins when not switching door", play(false));
console.log("Wins when switching door", play(true));</lang>
console.log("Wins when switching door", play(true));
</lang>

Output:

<lang javascript>
Playing 10000 games
Wins when not switching door 3326
Wins when switching door 6630
</lang>


=={{Header|Liberty BASIC}}==
=={{Header|Liberty BASIC}}==