蒙蒂霍尔程序模拟(C#)

时间:2013-04-25 11:46:03

标签: c# probability

我正在尝试模拟Monty Hall Problem(因为我从书中Think Statistics读到了一个人,特别是在看到计算机模拟后才被说服)在C#中,这是我最熟悉的编程语言。我的情况是,奖品的位置是随机的(在每次运行中),我的选择是随机的,游戏主持人选择打开门是随机的(如果我选择了非奖品,则不能随机)。

令人惊讶的是,无论我是否改变,我的计划都能实现50:50的胜算。这是它的代码(原谅我的长度):

class Program
{
    static void Main(string[] args)
    {
        Random rand = new Random();

        int noSwitchWins = RunGames(rand, false, 10000);
        int switchWins = RunGames(rand, true, 10000);

        Console.WriteLine(string.Format("If you don't switch, you will win {0} out of 1000 games.", noSwitchWins));
        Console.WriteLine(string.Format("If you switch, you will win {0} out of 1000 games.", switchWins));

        Console.ReadLine();
    }

    static int RunGames(Random rand, bool doSwitch, int numberOfRuns)
    {
        int counter = 0;

        for (int i = 0; i < numberOfRuns; i++)
        {
            bool isWin = RunGame(rand, doSwitch);
            if (isWin)
                counter++;
        }

        return counter;
    }

    static bool RunGame(Random rand, bool doSwitch)
    {
        int prize = rand.Next(0, 2);
        int selection = rand.Next(0, 2);

        // available choices
        List<Choice> choices = new List<Choice> { new Choice(), new Choice(), new Choice() };
        choices[prize].IsPrize = true;
        choices[selection].IsSelected = true;
        Choice selectedChoice = choices[selection];
        int randomlyDisplayedDoor = rand.Next(0, 1);

        // one of the choices are displayed
        var choicesToDisplay = choices.Where(x => !x.IsSelected && !x.IsPrize);
        var displayedChoice = choicesToDisplay.ElementAt(choicesToDisplay.Count() == 1 ? 0 : randomlyDisplayedDoor);
        choices.Remove(displayedChoice);

        // would you like to switch?
        if (doSwitch)
        {
            Choice initialChoice = choices.Where(x => x.IsSelected).FirstOrDefault();
            selectedChoice = choices.Where(x => !x.IsSelected).FirstOrDefault();
            selectedChoice.IsSelected = true;
        }

        return selectedChoice.IsPrize;
    }
}

class Choice
{
    public bool IsPrize = false;
    public bool IsSelected = false;
}

这完全是为了我自己的利益,我以最熟悉和最舒适的方式写下来。请随意提出自己的意见和批评,非常感谢!

3 个答案:

答案 0 :(得分:5)

rand.Next(0,2)

只返回0或1;上限是独占。你永远不会选择第三扇门(除非你换掉),第三扇门永远不会有奖品。你正在模拟错误的问题。

尝试改为:

rand.Next(0,3)

同样地:

int randomlyDisplayedDoor = rand.Next(0, 1);

只选择第一个候选门;应该是:

int randomlyDisplayedDoor = rand.Next(0, 2);

现在我们得到:

If you don't switch, you will win 3320 out of 1000 games.
If you switch, you will win 6639 out of 1000 games.

注意 - 当等于时,上限为包含 - 即rand.Next(1,1)始终返回1

答案 1 :(得分:1)

请参阅Random.Next(minValue, maxValue)

  

参数

     

minValue(最小值)   键入:System.Int32   返回的随机数的包含下限。

     

包括maxValue   键入:System.Int32   返回的随机数的独占上限。 maxValue必须大于或等于minValue。

答案 2 :(得分:1)

要添加到Marc的答案,您还可以使用Random.Next(Int32),因为您的下限是0,所以它只是:

rand.Next(3)