Algorithm Implementation/Simulation/Monty Hall problem

R
numsim = 100000 doors = 1:3 opendoor = function(x) { if (x[1]==x[2]) return(sample(doors[-c(x[1])], 1)) else return(doors[-c(x[1],x[2])]) } swapdoor = function(x) { return(doors[-c(x[1], x[2])]) } winner = sample(doors, numsim, replace=TRUE) choice = sample(doors, numsim, replace=TRUE) open = apply(cbind(winner, choice), 1, opendoor) newchoice = apply(cbind(open, choice), 1, swapdoor) # cat("without switching, won ",  round(sum(winner==choice)/numsim*100,1),"   percent of the time.\n", sep="") cat("with switching, won ", round(sum(winner==newchoice)/numsim*100,1),"   percent of the time.\n", sep="")

[from http://sas-and-r.blogspot.com/search?q=7.23]

Ruby
Another implementation

SAS
data mh; do i = 1 to 100000; prize = rand("TABLE",.333,.333); * Monty puts the prize behind a random door; initial_guess = rand("TABLE",.333,.333); * We make a random initial guess; * if the initial guess is right, Monte can open either of the others; * which means that player can switch to either of the other doors; if initial_guess eq prize then do; new_guess = initial_guess; * choose a door until it's different from the initial guess—that's the door we switch to; do until (new_guess ne initial_guess); new_guess = rand("TABLE",.333,.333); end; end; * If the initial guess was wrong, Monte can rule out only one of the other doors; * which means that we must switch to the right door; if initial_guess ne prize then new_guess = prize; output; end; run; *; data mh2; set mh; win_by_keep = (initial_guess eq prize); win_by_switch = (new_guess eq prize); run; *; proc means data = mh2 mean; var win_by_keep win_by_switch; run;

[from http://sas-and-r.blogspot.com/search?q=7.23]