# This function simulates one trial of the Monty Hall problem, in which the
# contestant employs the always-stay strategy. The function returns the number
# of cars won (either 0 or 1).
alwaysStay <- function() {
# Doors are 0, 1, 2.
carDoor <- sample.int(n=3, size=1) - 1
pickedDoor <- sample.int(n=3, size=1) - 1
# Monty's opened door is never used, but let's go through the motions.
if (pickedDoor == carDoor)
openedDoor <- (sample.int(n=2, size=1) + pickedDoor) %% 3
else
openedDoor <- 3 - pickedDoor - carDoor
# Ignore the opened door.
newDoor <- pickedDoor
as.numeric(newDoor == carDoor)
}
# Here are 100 trials.
replicate(100, alwaysStay())
# Here is the total number of cars won in 100 trials.
sum(replicate(100, alwaysStay()))
# This function simulates one trial using the always-switch strategy.
alwaysSwitch <- function() {
# Doors are 0, 1, 2.
carDoor <- sample.int(n=3, size=1) - 1
pickedDoor <- sample.int(n=3, size=1) - 1
if (pickedDoor == carDoor)
openedDoor <- (sample.int(n=2, size=1) + pickedDoor) %% 3
else
openedDoor <- 3 - pickedDoor - carDoor
# This time, we do not ignore the opened door.
newDoor <- 3 - pickedDoor - openedDoor
as.numeric(newDoor == carDoor)
}
# Here is the total number of cars won in 100 trials.
sum(replicate(100, alwaysSwitch()))
# Try increasing the number of trials from 100 to 1,000,000. The simulation
# still takes less than a minute on my machine, and the results should more
# accurately reflect the 1 / 3 and 2 / 3 probabilities.