Last active
June 9, 2016 09:58
-
-
Save secretorange/ddb6da14ee2f1a5fa182739200f5e793 to your computer and use it in GitHub Desktop.
Monty Hall Simulation https://en.wikipedia.org/wiki/Monty_Hall_problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Monty Hall Problem
Looks like you're always better to switch: