Created
January 9, 2021 16:47
-
-
Save XerxesZorgon/d8d9f93c9bd55170fb4f95d5887e89ba to your computer and use it in GitHub Desktop.
Simulates the Monty Hall problem in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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