Created
January 24, 2024 10:59
-
-
Save TimTeaFan/86cace18db3befca020deda4cc5d5fef to your computer and use it in GitHub Desktop.
Monty Hall Problem
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
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