Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Created November 24, 2025 08:46
Show Gist options
  • Select an option

  • Save abikoushi/8640d78274c9e3607511fa8a30b61d5e to your computer and use it in GitHub Desktop.

Select an option

Save abikoushi/8640d78274c9e3607511fa8a30b61d5e to your computer and use it in GitHub Desktop.
モンティ・ホール問題のシミュレーション
library(dplyr)
library(gt)
doors = LETTERS[1:3]
policy1 = 0L
policy2 = 0L
iter = 100000
res_raw = matrix(NA_character_, iter, 4)
set.seed(1124)
system.time({
for(i in 1:iter){
hit = sample(doors,1)
choice1 = sample(doors,1)
open = sample(setdiff(doors,c(hit,choice1)),1)
choice2 = sample(setdiff(doors,c(open,choice1)),1)
policy2 = policy2 + as.integer(choice2 == hit)
policy1 = policy1 + as.integer(choice1 == hit)
res_raw[i,] = c(hit,choice1,open,choice2)
}
})
# user system elapsed
# 3.129 0.012 3.213
print(policy1/iter) #0.33486 = 1/3
print(policy2/iter) #0.66514 = 2/3
colnames(res_raw) <- c("hit", "choice1", "open", "choice2")
res_sum <- as.data.frame(res_raw) %>%
group_by(hit,choice1,open,choice2) %>%
tally() %>%
ungroup() %>%
arrange(hit, choice1, open, choice2) %>%
mutate(prob = n/sum(n)) %>%
select(-n)
t1 = gt(res_sum)
t1
gtsave(t1,"tab1.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment