Skip to content

Instantly share code, notes, and snippets.

@XerxesZorgon
Created January 9, 2021 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XerxesZorgon/d8d9f93c9bd55170fb4f95d5887e89ba to your computer and use it in GitHub Desktop.
Save XerxesZorgon/d8d9f93c9bd55170fb4f95d5887e89ba to your computer and use it in GitHub Desktop.
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