# Monty Hall problem simulation
#
# 	...modified on 2017.11.26 (05:17)
#
rnd3 <- function() {
  trunc(runif(1) * 3)
}
game <- function(ch_door = F) {
  prize <- rnd3()
  choice <- rnd3()
  while (TRUE) {
    open_door <- rnd3()
    if (open_door != choice & open_door != prize) break
  }
  if (ch_door == T) {
    for(new_choice in 0:2) {
      if (new_choice != choice & new_choice != open_door) break
    }
    choice <- new_choice
  }
  if (choice == prize) return(1)
  else return(0)
}

play <- function(n, ch_door) {
  point <- 0.0
  for (i in 1:n) point <- point + game(ch_door)
  return(point)
}

num <- 10000

# print(sprintf('Rate if not change: %1.4f',play(num,F)/num))
# print(sprintf('Rate if change: %1.4f',play(num,T)/num))

講義用スタイル
印刷用スタイル