# Monty Hall Problem -- Solve using loops, step by step # Chris Adolph # 1/6/2005 sims <- 10000 # Simulations run doors <- c(1,0,0) # The car (1) and the goats (0) cars.chosen <- 0 # Save cars from first choice here cars.rejected <- 0 # Save cars from switching here for (i in 1:sims) { # Loop through simulations # First, contestant picks a door first.choice <- sample(doors, 3, replace=FALSE) # Choosing a door means rejecting the other two chosen <- first.choice[1] rejected <- first.choice[2:3] # Monty Hall removes a goat from the rejected doors rejected <- sort(rejected) if (rejected[1]==0) rejected <- rejected[2] # Record keeping: where was the car? cars.chosen <- cars.chosen + chosen cars.rejected <- cars.rejected + rejected } cat("Probability of a car from staying with 1st door", cars.chosen/sims,"\n") cat("Probability of a car from switching to 2nd door", cars.rejected/sims,"\n")