# Simulate one play of the Monty Hall game. The player is assumed to # choose a door at random to start. If the argument of the function # is TRUE, the player switches doors when offerred a choice; if FALSE, # they don't switch. The value returned is a list containing the # doors chosen, opened, and with the car. one.play <- function (switch) { # Randomly choose which door has the car behind it, # and which door the player initially chooses. door.with.car <- sample (1:3, 1) door.chosen <- sample (1:3, 1) # Decide which door Monty Hall opens, choosing randomly from # among doors other than the one chosen and the one with the car. # This is done by repeatedly picking from among all three doors # until one that isn't excluded is chosen. repeat { door.opened <- sample(1:3, 1) if (door.opened!=door.chosen && door.opened!=door.with.car) { break } } # Have the player switch doors, if they're doing that. They switch # to whichever door wasn't opened and isn't their current door. if (switch) { for (i in 1:3) { if (i!=door.chosen && i!=door.opened) { door.chosen <- i break } } } # Return a list recording what happened. list (door.with.car=door.with.car, door.chosen=door.chosen, door.opened=door.opened) } # Simulate many plays of the Monty Hall game, recording how often the # player wins the car. The first argument is the number of plays to # simulate. The second argument says whether or not the player # switches doors when given the chance. The value returned is the # fraction of times the player won. many.plays <- function (n.plays, switch) { # Simulate playing the game n.plays times, counting the number of wins. n.wins <- 0 for (i in 1:n.plays) { p <- one.play(switch) if (p$door.chosen == p$door.with.car) { n.wins <- n.wins + 1 } } # Return the fraction of plays when the player wins the car. n.wins / n.plays }