Created
May 24, 2010 06:37
-
-
Save hadronzoo/411593 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
% Run a Monty Hall problem simulation with the following parameters: | |
% | |
% changeDoors: boolean determining whether the contestant should change | |
% doors | |
% | |
% doors: the number of doors in the problem, with a minimum of 2 | |
% | |
% N: the number of problem simulations to perform, with a minimum | |
% of 1 | |
% | |
% returns [runs, Pr], where runs is an array with N rows, each with the | |
% following columns: | |
% 1) the door originally picked | |
% 2) the other door left closed | |
% 3) the door finally picked | |
% 4) the door the prize was behind | |
% 5) a boolean representing whether the contestant won | |
% | |
% and with Pr being the proportion of games won by the contestant | |
function [runs, Pr] = runMontyHallSim(changeDoors, doors, N) | |
% Minimum of 1 run with 2 doors | |
N = max(N, 1); | |
doors = max(doors, 2); | |
% Allocate runs array | |
runs = zeros(N, 5); | |
for i = 1:N | |
prizeDoor = randi(doors); | |
originalDoorPicked = randi(doors); | |
% What would Monty Hall do? If the contestant picks the prize door, | |
% leave one of the other doors closed, chosen at random. | |
if (prizeDoor == originalDoorPicked) | |
otherDoorLeftClosed = randi(doors); | |
while (otherDoorLeftClosed == originalDoorPicked) | |
otherDoorLeftClosed = randi(doors); | |
end | |
else % Otherwise, leave the prize door closed | |
otherDoorLeftClosed = prizeDoor; | |
end | |
if (changeDoors) | |
doorFinallyPicked = otherDoorLeftClosed; | |
else | |
doorFinallyPicked = originalDoorPicked; | |
end | |
contestantWon = (doorFinallyPicked == prizeDoor); | |
runs(i,:) = [originalDoorPicked, otherDoorLeftClosed, ... | |
doorFinallyPicked, prizeDoor, contestantWon]; | |
end | |
Pr = sum(runs(:,5))./N; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is an overview of the problem. MacKay's excellent Information Theory, Inference, and Learning Algorithms, which is freely downloadable, has an in-depth discussion of the problem in the solutions to Exercises 3.8 and 3.9 (pages 57, 60, and 61).
By the way, this is Matlab or Octave code.