这是我为解决问题而编写的最终代码。我使用 if 语句仅在必要时调用 sample,这是候选人选择车门的情况。我觉得听到额外的条件语句比强迫样本以非预期方式工作的成本更有价值。
doors <- 1:3
trials <- 1000
games <- do.call(rbind, lapply(1:trials, function(i){
pick <- sample(doors, 1)
car <- sample(doors, 1)
#open the door the contestant didn't pick and isn't the car
open_door <- setdiff(doors, c(pick, car))
#if pick and car are the same, there are two possible doors to open
#so pick one at random
#note, sample will malfunction if there is only 1 int passed to it. See documentation.
#this is the reason for if statement, only deal with the case where there is more than
#one int passed
if(length(open_door)>1) open_door <- sample(open_door, 1)
#switch to the door that isn't picked and is closed
switch_to <- setdiff(doors, c(pick, open_door))
data.frame(pick, car, open_door, switch_to)
}))
games$switch_wins <- ifelse(games$switch_to == games$car, 1, 0)
games$stay_wins <- ifelse(games$pick == games$car, 1, 0)
cat("Switch wins: ", sum(games$switch_wins)/nrow(games), "Stay wins: ",
sum(games$stay_wins)/nrow(games), "\n")
输出:
Switch wins: 0.672 Stay wins: 0.328