function montyHall2(n,d,o)
%montyhall(n,d,o) Simulates n rounds of the Monty Hall problem and
% gives win/loss ratio
%
% n : Number of rounds to simulate (Any positive integer)
% d : Number of doors (Positive integer >= 3)
% o=0 : Show final win/loss score and estimated probability
% o=1 : Show win/loss tally chart and estimated probability
% o=2 : Show results for each round
%
% All parameters are optional, by default they will take the values:
% n=1, d=3, o=0.
%
% The Monty Hall problem is a probability puzzle based on the American
% television game show Let's Make a Deal. The name comes from the show's
% host, Monty Hall. The problem is also called the Monty Hall paradox,
% as it is a veridical paradox in that the result appears absurd but is
% demonstrably true.
%
% Reference: http://en.wikipedia.org/wiki/Monty_Hall_problem
win=0;
lose=0;
tally=[0;0];
Monty=0;
% Check for nonexistent variables and set to defaults
if exist('n')~=1
n=1;
end
if exist('d')~=1 || d<3 || d~=round(d)
d=3;
end
if exist('o')~=1
o=0;
end
if o==2
for i = 1:n
% Picks a random door for the car to be behind
Car = randi(d)-1;
% Player picks a random door
Choose = randi(d)-1;
% Monty recursively picks a random door until he has chosen
% the door that neither has the car behind it or has been
% chosen by the player
while (Monty==Car || Monty==Choose)
Monty=randi(d)-1;
end
% If you originally choose the car, no matter what door Monty
% opens, you will lose by switching.
% If you originally choose a goat, Monty has to open a door to
% reveal the other goat, and switching will switch to the car
% meaning you win.
% Simply put, if you originally choose the car, switching wins
% and if you don't, switching loses.
% This is the basis of the score tally system
if Choose==Car
lose=lose+1;
else
win=win+1;
end
% Display round results after game has been played.
disp(['Round ',num2str(i)]);
disp('Chosen door:');
disp([zeros(1,Choose),1,zeros(1,(d-1)-Choose)]);
if CarChoose
disp('Monty opens:');
disp([ones(1,Choose),0,ones(1,Car-Choose-1),0,ones(1,(d-1)-Car)]);
end
if Car == Choose
if Car=10
disp(['Estimated Chance Of Winning After Switch: ',num2str(win/n)]);
end
end