# 'Monty Hall paradox' simulation # see http://en.wikipedia.org/wiki/Monty_Hall_problem # for more R-scripts: www.random-stuff.de durchg = 100 durchg <- sqrt.durchg^2 result <- c() pdf("Monty-Hall-no-change.pdf", width=7, height=9) par(mfcol=c(durchg/10,durchg/10), xaxt="n", yaxt="n", bty="o", omi=c(0,0,0,0), mai=c(0,0,0,0)) for(i in 1:durchg) { win <- sample(1:3, 1) choice <- sample(1:3, 1) plot(c(), c(), xlim=c(1,10), ylim=c(1,11), xlab="", ylab="") if(win == 1) { rect(1.5,2,3.5,7, col="darkblue") } else { rect(1.5,2,3.5,7) } if(win == 2) { rect(4.5,2,6.5,7, col="darkblue") } else { rect(4.5,2,6.5,7) } if(win == 3) { rect(7.5,2,9.5,7, col="darkblue") } else { rect(7.5,2,9.5,7) } if(choice == 1) { points(2.5,8, bg="darkblue", cex=1.2, pch=21) } else if(choice == 2) { points(5.5,8, bg="darkblue", cex=1.2, pch=21) } else { points(8.5,8, bg="darkblue", cex=1.2, pch=21) } if(win == choice) { result <- c(result, 1) title(main="WON!", line=-1, col.main="forestgreen", cex.main=0.9) } else { result <- c(result, 0) } } result.no.change <- sum(result) / length(result) result.no.change.lost <- length(result) - sum(result) result.no.change.won <- sum(result) #quartz.save("Monty-Hall-no-change.pdf", type="pdf") # for Mac PCs dev.off() result <- c() pdf("Monty-Hall-change.pdf", width=7, height=9) par(mfcol=c(durchg/10,durchg/10), xaxt="n", yaxt="n", bty="o", omi=c(0,0,0,0), mai=c(0,0,0,0)) for(i in 1:durchg) { win <- sample(1:3, 1) choice1 <- sample(1:3, 1) x <- c(1:3) open <- x[x != win & x != choice1] if (length(open)==2) { open<-sample(open,1) } else {open <- open } choice2 <- x[x != choice1 & x != open] plot(c(), c(), xlim=c(1,10), ylim=c(1,11), xlab="", ylab="") if(win == 1) { rect(1.5,2,3.5,7, col="darkblue") } else { rect(1.5,2,3.5,7) } if(win == 2) { rect(4.5,2,6.5,7, col="darkblue") } else { rect(4.5,2,6.5,7) } if(win == 3) { rect(7.5,2,9.5,7, col="darkblue") } else { rect(7.5,2,9.5,7) } if(choice2 == 1) { points(2.5,8, bg="darkblue", cex=1.2, pch=21) } else if(choice2 == 2) { points(5.5,8, bg="darkblue", cex=1.2, pch=21) } else { points(8.5,8, bg="darkblue", cex=1.2, pch=21) } if(win == choice2) { result <- c(result, 1) title(main="WON!", line=-1, col.main="forestgreen", cex.main=0.9) } else { result <- c(result, 0) } } result.change <- sum(result) / length(result) result.change.lost <- length(result) - sum(result) result.change.won <- sum(result) dev.off() results <- matrix(c(result.no.change.lost, result.no.change.won, result.change.lost, result.change.won), nrow=2, ncol=2, byrow=T) colnames(results) <- c("times lost", "times won") rownames(results) <- c("no change strategy", "change strategy") write.csv2(results, file="Monty-Hall-results", quote=F) print(paste("Data were saved in:", getwd()))