Skip to content

Instantly share code, notes, and snippets.

@secretorange
Last active June 9, 2016 09:58
Show Gist options
  • Save secretorange/ddb6da14ee2f1a5fa182739200f5e793 to your computer and use it in GitHub Desktop.
Save secretorange/ddb6da14ee2f1a5fa182739200f5e793 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
namespace MontyHall
{
public class Game
{
private static Random Random = new Random();
public static void Main(string[] args)
{
const int TRIES = 1000000;
var stayWins = PlayGame(TRIES, false);
PrintResult("Stay strategy", TRIES, stayWins);
var switchWins = PlayGame(TRIES, true);
PrintResult("Switch strategy", TRIES, switchWins);
Console.ReadLine();
}
private static void PrintResult(string game, int numberOfTries, int wins)
{
Console.WriteLine(game + ": " + ((float) wins / numberOfTries * 100) + "% wins");
}
private static int PlayGame(int numberOfTries, bool switchDoor)
{
var doors = new[] { "Car", "Goat", "Goat" };
var indexes = new[] { 0, 1, 2 };
int wins = 0;
for (var i = 0; i < numberOfTries; i++)
{
Random.Shuffle(doors);
var choice = Random.Next(0, 3);
var car = Array.IndexOf(doors, "Car");
if (switchDoor)
{
int reveal;
while (true)
{
reveal = Random.Next(0, 3);
if (reveal != choice && doors[reveal] != "Car")
break;
}
choice = indexes.SingleOrDefault(index => index != reveal && index != choice);
}
if (choice == car)
wins++;
}
return wins;
}
}
static class RandomExtensions
{
public static void Shuffle<T>(this Random rng, T[] array)
{
int n = array.Length;
while (n > 1)
{
int k = rng.Next(n--);
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
}
}
@secretorange
Copy link
Author

Monty Hall Problem

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?
https://en.wikipedia.org/wiki/Monty_Hall_problem

Looks like you're always better to switch:

output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment