[Math] How to simulate Monty Hall problem in computer

MATLABmonty-hallprobability

Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1 [but the door is not opened], and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?

This is Monty Hall problem, and we know that a switching strategy really does win two out of three times on the average. But is it possible to simulate it in Matlab?

Best Answer

Some pseudocode:

  1. Set winswap = 0, winnoswap = 0 and simcount = 0.
  2. Increment simcount by 1.
  3. Set car = random value from a choice of $\{ 1, 2, 3\}$.
  4. Set guess = random value from a choice of $\{1, 2, 3\}$.
  5. Set goat = random value from a choice of $\{1, 2, 3\}$ that is not equal to either car or guess.
  6. Set swap = random value from a choice of $\{1, 2\}$.
  7. If swap = 2, set guess = the first value of $\{1, 2, 3\}$ that is not equal to either goat or guess.
  8. If guess = car and swap = 1, increment winnoswap by 1.
    If guess = car and swap = 2, increment winswap by 1.
  9. If simcount is below some predetermined value, return to step 2.
  10. Compare the values of winswap and winnoswap.