###################
#A simulation of the Monty Hall Problem
###################
sim.size = 10000
doors = c("door1", "door2", "door3") #define 3 doors
results=rep(0,times=sim.size) #define a data structure to save our results
for(i in 1:sim.size) { #we need to loop this in order to simulate it
#step 1: place the prize behind a random door --- we are letting this vary so that it is a simulation of the gameshow itself. We want to see how often the contestant wins by keeping their door, and how often they win by switching doors
prize.door=sample(doors, 1)
#step 2: have the constestant choose a door. Again, this is random, because we want to simulate the gameshow over time
pick.door=sample(doors, 1)
#step 3: list the doors that have no prize behind them and have not been picked; these are the doors that Monty can choose from.
remaining=subset(doors, doors != prize.door & doors != pick.door)
#step 4: have Monty choose a door from the remaining doors (this is random, but it is only from the set of doors that don't have a prize and haven't been chosen by a contestant)
open.door = sample(remaining,1)
#step 5: Define the door that would be the "switch door" if the contestant decided to switch. Basically, this is the door that wasn't chosen initially and wasn't opened
switch.door=doors[doors != pick.door & doors != open.door] #define the door that would be the switch
#step 6: Calculate what happens. You can define this any way that you want. I am defining it as "stay win" and "switch win", because I want to know which is the better strategy.
if(pick.door==prize.door){results[i]="stay.win"}
if(switch.door==prize.door) {results[i]="switch.win"}
} #end loop
#Step 7: count the results
length(results[results=="stay.win"])
length(results[results=="switch.win"])
#step 8: convert to probabilities?
length(results[results=="stay.win"])/sim.size
length(results[results=="switch.win"])/sim.size