Skip to content

Instantly share code, notes, and snippets.

@hadronzoo
Created May 24, 2010 06:37
Show Gist options
  • Save hadronzoo/411593 to your computer and use it in GitHub Desktop.
Save hadronzoo/411593 to your computer and use it in GitHub Desktop.
% 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;
@hadronzoo
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment