Skip to content

Instantly share code, notes, and snippets.

@TimTeaFan
Created January 24, 2024 10:59
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 TimTeaFan/86cace18db3befca020deda4cc5d5fef to your computer and use it in GitHub Desktop.
Save TimTeaFan/86cace18db3befca020deda4cc5d5fef to your computer and use it in GitHub Desktop.
Monty Hall Problem
reveal_door <- function(doors) {
if ("car" %in% names(doors)) {
return(doors[names(doors) != "car"])
}
sample(doors, size = 1)
}
play_monty_hall <- function(switch_doors = FALSE) {
# setup the doors 1 to 3 randomly
door_names <- sample(c("goat", "goat", "car"), size = 3, replace = FALSE)
three_doors <- setNames(1:3, nm = door_names)
# player chooses door
chosen_door <- sample(three_doors, size = 1)
# in case player uses "switching strategy"
if (switch_doors) {
remaining_doors <- three_doors[-chosen_door]
revealed_door <- reveal_door(remaining_doors)
finally_remaining_door <- remaining_doors[remaining_doors != revealed_door]
chosen_door <- finally_remaining_door
}
# check if player gets car
names(chosen_door) == "car"
}
sum(replicate(10000, play_monty_hall(switch_doors = FALSE)))
sum(replicate(10000, play_monty_hall(switch_doors = TRUE)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment