====== Řešení Monty Hall problému počítačovou simulací ======
no.rep <- 1000 # how many times to repeat the game
win.chan <- logical (0) # would you win if you changed your opinion?
win.no.chan <- logical (0) # would you win if you did NOT changed your opinion?
for (i in seq (no.rep))
{
# which door hide Maserati?
m <- sample (c (1,2,3), 1)
# which door the guest randomly choose?
g <- sample (c (1,2,3), 1)
# which door the host should open?
if (g == m) h <- sample (c(1,2,3)[!c(1,2,3) == g],1) else h <- c(1,2,3)[!c(1,2,3) %in% c(m, g)]
# if the guest decided to change his decision:
chan <- c(1,2,3)[!c (1,2,3) %in% c (g,h)]
win.chan <- append (win.chan, chan == m)
# if the guest decided not to change his decision:
win.no.chan <- append (win.no.chan, m == g)
}
# probability that the guest win if he didn't change
sum (win.no.chan)/no.rep
# probability that the guest win if he decided to change
sum (win.chan)/no.rep
Další varianta - daleko kratší řešení
no.rep <- 1000
matice <- matrix (NA, nrow = no.rep, ncol =3)
for (i in seq (1, no.rep)) matice[i,] <- sample (c(1,0,0), 3) # 1 equals to doors with Maserati
# probability that the guest win if he didn't change (e.g. he always choose the doors no 3)
sum (matice [,3])/1000
# probability that the guest win if he decided to change:
sum (rowSums (matice [,-3]))/1000
# Note: guest originally always choose the third door, and he will always change;
# in this case it's not important to know, which another door he will choose - we can be sure,
# that in the other door, which the host opens, is always goat, and that in the doors the guest
# choose is either goat (if Maserati is in the third door) or Maserati.