Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simulates the Monty Hall problem in R
# Monty Hall problem simulation
#
# Parameters
# ----------
# n: Number of samples
#
# Returns
# -------
# p: Probability of winning
#
# Written by John Peach, 08 Jan 2021
montyhall <- function(n)
{
# Win counter
wins <- 0
# Loop over n samples, rolling a pair of dice
for(i in 1:n){
# Roll the dice
s <- sample(3,2,replace = TRUE)
# If the doors are different, win the car
if(s[1] != s[2]) wins = wins + 1
}
# Calculate the probability of winning
p <- wins/n
# Print the result
print(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment