# Simulating the "Monty Hall Problem"

I was reading about the "Monty Hall Problem" this afternoon and in an attempt to simulate it I wrote some code. The following should run in Matlab / GNU Octave. Results agree with the theory.

The results of running the code are shown in the image attached. The probability converges on 2/3 as expected. After some more grappling with the problem I think I finally understand the solution.

In the event that you pick a goat on the first selection, 'Monty' will eliminate the remaining goat, and you will always switch to a car. The chances of picking a goat on the first attempt are 2/3. So switching is actually the correct answer.

Code:

% Code to simulate the monty hall problem % The array 'doors' represent the 3 doors % Door States: % 0 - uninitialized % 1 - car % 2 - goat % 3 - revealed % % Neil Dick % % clear everything.. clc clear all close all %Initialize numOfSimulatedGames = 100000; numGamesPlayed = 0; successfulSwitch = 0; probabilityOfSuccess=zeros(1,numOfSimulatedGames); for numGamesPlayed = 1:numOfSimulatedGames doors = zeros(1,3); % Stick a car behind a random door rNum = 3*rand(); if( (rNum>0) && (rNum<1)) doors(1) = 1; elseif( (rNum>1) && (rNum<2)) doors(2) = 1; else doors(3) = 1; end % Fill in the other 2 spots with goats.. for i = 1:3 if(doors(i)==0) doors(i) = 2; end end % Have contestant randomly pick a door. rNum = 3*rand(); if( (rNum>0) && (rNum<1)) chosenDoor = 1; elseif( (rNum>1) && (rNum<2)) chosenDoor = 2; else chosenDoor = 3; end % Reveal the first goat door that isnt a chosen door. picked = 0; for i = 1:3 if(i~=chosenDoor) if(doors(i)~=1) if(picked==0) %door isn't a car, isn't the one the contestant picked, and we havent revealed yet.. doors(i)=3; picked =1; end end end end % At this point the theory says it's beneficial to switch your choice. % so, if the door that (hasn't been picked or revealed) is the car, increment % a variable and calculate the probabiltiy. for i = 1:3 if(i~=chosenDoor) if(doors(i)~=3) %Not chosen or revealed, must be the door we'd switch too.. if(doors(i)==1) %If we would have switched and won the car successfulSwitch = successfulSwitch+1; end end end end probabilityOfSuccess(numGamesPlayed) = successfulSwitch / numGamesPlayed; end xaxis = 1:numGamesPlayed; figure plot(xaxis,probabilityOfSuccess); xlabel('Number of games played') ylabel('Probability of a succesful switch')

In the event that you pick a goat on the first selection, 'Monty' will eliminate the remaining goat, and you will always switch to a car. The chances of picking a goat on the first attempt are 2/3. So switching is actually the correct answer.

Total Comments 0