Click here to Skip to main content
Licence CPOL
First Posted 31 Oct 2006
Views 39,714
Downloads 108
Bookmarked 10 times

The Monty Hall Problem - C# Solution

By | 6 Nov 2006 | Article
C# Solution to the "Monty Hall Problem"

Introduction

In a recent episode of Numb3rs, the television drama sometimes involving the theoretical use of mathematics to solve real world crime problems "Charlie" the Mathematician gave a public seminar demonstrating some math's puzzles. One of those demonstrated was the "Monty Hall ParadoxWikipedia describes this puzzle as:

"The Monty Hall problem is a puzzle involving probability loosely based on the American game show Let's Make a Deal. The name comes from the show's host, Monty Hall. A widely known, but problematic (see below) statement of the problem is from Craig F. Whitaker of Columbia, Maryland in a letter to Marilyn vos Savant's September 9, 1990, column in Parade Magazine (as quoted by Bohl, Liberatore, and Nydick).

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, 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?"

The question in a nutshell is, after the host removes one of the wrong doors, is there any advantage to changing your answer. Is it now a 50/50 chance? Or does staying or changing your selection increase OR decrease your odds of winning?

The Experiment

I wrote a simple console application that run 1 million iterations of The Monty Hall gameshow segment. The proof carries out the following process:

  1. Randomly choose 1 of 3 doors for the initial contestant's pick
  2. Randomly pick one of the wrong doors to remove (the host knows which one has the car, and removes an INCORRECT choice)
  3. Change the contestant's picked door
  4. Determine if the contestant WON or LOST!

Did the contestant win after switching?

Result when SWITCHING your choice after the host has removed one incorrect answer:

Wins: 666576 Losses: 333424 Total: 1000000

If you initially think that there is no advantage in switching doors, or your probability is 50/50, or your probability remains at 1 out of 3 - you are in great company, but still INCORRECT.

Switching your initial choice after the host has disclosed one incorrect door DOUBLES your chances of winning to 2 out of 3.

I must admit, until I wrote this proof I wasn't exactly confident. It clearly demonstrates that approximate 66% of the time you would WIN if you SWITCHED your answer, and only win 33% of the time if you kept your initial choice.

I was also amazed at the almost perfect ratio 66.6 / 33.3 which matched the theoretical 2 out of 3 win/loss prediction. Kudos to the authors of the built-in .NET Random class. I didn't initially believe the results because the numbers worked out so nice, but I've double-checked my code and made certain that I've used random decisions for all moving parts. I'd be interested if anyone can point-out anything wrong with my code though.

The Code

using System;

namespace MontyHall
{
    class Program
    {
        static void Main(string[] args)
        {
            // local variables to hold result and random generator
            Random random = new Random();
            int wins   = 0;
            int losses = 0;

            // iterate our MontyHall routine
            for (int i = 0; i < 1000000; i++)
            {
                // changeDoor: 
                // 0 = no, the contestant stays with their initial pick,
                // after the offer to switch after
                // the disclosure of a "Goat" door
                // 1 = yes, the contestant chose to switch doors after
                // the disclosure of a "Goat" door
                //int changeDoor = 0;
                int changeDoor = 1;
                
                // calculate whether or not the contestant wins the Car -
                // random pickedDoor: 0, 1 or 2 for the door
                // the contestant initially picked
                // changeDoor: 0 = no, 1 = yes. The contentment decides
                // to change their selection after disclosure of a "Goat" door
                // random carDoor: 0, 1 or 2 for the door containing the car
                // random goatDoorToRemove: 0 = leftmost Goat door,
                // 1 = rightmost Goat door. Monty discloses
                // one incorrect door, this value indicates which one.
                bool result = MontyHallPick(random.Next(3), changeDoor, 
                                            random.Next(3), random.Next(1));

                if (result) 
                    wins++;
                else
                    losses++;
            }

            Console.WriteLine("Wins: {0} Losses: {1}  Total: {2}", 
                              wins, losses, wins+losses);
            Console.ReadLine();        
        }

        public static bool MontyHallPick(int pickedDoor, int changeDoor, 
                                      int carDoor, int goatDoorToRemove)
        {
            bool win = false;

            // randomly remove one of the *goat* doors,
            // but not the "contestants picked" ONE!
            int leftGoat  = 0;
            int rightGoat = 2;
            switch (pickedDoor)
            {
                case 0: leftGoat = 1; rightGoat = 2; break;
                case 1: leftGoat = 0; rightGoat = 2; break;
                case 2: leftGoat = 0; rightGoat = 1; break;
            }

            int keepGoat = goatDoorToRemove == 0 ? rightGoat : leftGoat;

            // would the contestant win with the switch or the stay?
            if (changeDoor == 0)
            {
                // not changing the initially picked door
                win = carDoor == pickedDoor;
            }
            else
            {
                // changing picked door to the other door remaining
                win = carDoor != keepGoat;
            }

            return win;
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Troy Magennis

Web Developer

United States United States

Member

Troy Magennis is a C# MVP, born and raised in Sydney, Australia but now living in Seattle, WA in the United States. Troy spends whatever time he doesn't spend writing or talking about writing C# .NET code in the outdoors, hiking or skiing. Current hobby projects include writing about the upcoming C# features, writing a suit of unit tests for the Standard Query Operators for LINQ, and a set of additional extension methods all available from his Blog: http://blog.aspiring-technology.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionWhat if... PinmemberWarrick Procter18:16 13 Jan '08  
QuestionCannot how to work Solution Explorer PinmemberMember #388677021:43 4 Mar '07  
QuestionCannot how to work Solution Explorer PinmemberMember #388677021:41 4 Mar '07  
QuestionCannot how to work Solution Explorer PinmemberMember #388677021:29 4 Mar '07  
GeneralSimplest terms Pinmembervsg91015:04 21 Nov '06  
GeneralRe: Simplest terms Pinmembervsg91015:18 21 Nov '06  
GeneralAn intuitive comment ... a more formal approach PinmemberMaurice Tarrant19:12 14 Nov '06  
GeneralRe: An intuitive comment ... a more formal approach Pinmembergregmulvihill15:25 5 Feb '07  
GeneralAn intuitive comment ... PinmemberMaurice Tarrant16:29 14 Nov '06  
I offer the following comment, without having read anyone else's comments and without having looked at the code, because I don't want to be influenced by the author's or other members' opinions.
 
My reasoning requires that it can be safely assumed by the contestant that the door which will be removed has certainly got a goat behind it (I am not familiar with the game format).
 
It follows from that that once that door for removal has been nominated, the car is behind one or the other of the remaining doors. It cannot matter which door the contestant has first nominated, because she is allowed to choose afresh. The question "Do you want to pick door No. x?" is the same as asking the contestant to nominate one of only two doors available. One hides the car, the other doesn't. It is irrelevant what choice had been made earlier. The probability of winning is 50%.
 
Putting it in quite another way - suppose there are thirty three doors when the contestant arrives on the stage and it is known that they conceal thirty two goats and one car. Suppose too that someone simply walks onto the stage and removes thirty one doors. The contestant can have as many choices and changes of minds as she likes, before settling on one - she has a 50% chance of winning as long as there are only ever two doors to choose from.
 
Now I will have a look at what others have written!

GeneralLight dawns! PinmemberDave Cross23:27 13 Nov '06  
JokeCongratulations ... PinmemberIlíon4:10 7 Nov '06  
GeneralWell, while you're at it PinmemberCliffStanford6:43 1 Nov '06  
GeneralFunction flaw [modified] Pinmemberfera3:45 1 Nov '06  
GeneralRe: Function flaw PinmemberTroy_Magennis7:57 1 Nov '06  
GeneralRe: Function flaw Pinmemberfera9:39 2 Nov '06  
GeneralNot a proof Pinmemberjuggler2:53 1 Nov '06  
GeneralRe: Not a proof PinmemberTroy_Magennis7:58 1 Nov '06  
QuestionWhy? PinmemberPaul Watt19:23 31 Oct '06  
AnswerRe: Why? Pinmembercykophysh3922:30 31 Oct '06  
AnswerRe: Why? Pinmemberjoelgarabedian23:46 31 Oct '06  
AnswerRe: Why? PinmemberRexNebular1:15 1 Nov '06  
GeneralRe: Why? Pinmemberhomerbush5:27 1 Nov '06  
GeneralRe: Why? PinmemberDancnDude9:56 13 Nov '06  
AnswerRe: Why? PinmemberJames Curran5:24 1 Nov '06  
GeneralRe: Why? PinmemberSteven Roebert8:32 1 Nov '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 6 Nov 2006
Article Copyright 2006 by Troy Magennis
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid