


### MONTY HALL PROBLEM ###

# 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, 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()))

# The following code estimates the probability of winning under both 
# strategies. To get more accurate results, at the expense of computational 
# time, try increasing the number of trials. Even 1,000,000 trials take my 
# computer only a few seconds.
numTrials <- 1000000
sum(replicate(numTrials, alwaysStay())) / numTrials
sum(replicate(numTrials, alwaysSwitch())) / numTrials


