CSharp · Console
using System;
using System.Collections.Generic;
int wins = 0;
int losses = 0;
int attempts = 0;
int numberOfDoors = 3;
Random random = new Random();
// Main game loop. Number of simulations can easily be changed from 1000
for (int games = 0; games < 1000; games++)
{
List<Door> doors = new List<Door>();
for (int i = 0; i < numberOfDoors; i++)
{
doors.Add(new Door { Contents = "goat", Opened = false, PlayerChoice = false, });
}
// Randomly pick a door for the car to be in
int doorNumWithCar = random.Next(0, numberOfDoors);
doors[doorNumWithCar].Contents = "car";
// I set player choice to always be door #1 to make it simpler
doors[0].PlayerChoice = true;
// Monty randomly removes one of the 2 doors not chosen by the player.
// (obviously, he doesn't remove the door with the car)
int doorMontyOpens;
while (doors.Count != 2)
{
doorMontyOpens = -1;
while (doorMontyOpens == -1)
{
int possibleDoorToBeShown = random.Next(1, doors.Count);
if (doors[possibleDoorToBeShown].Contents != "car")
{
doorMontyOpens = possibleDoorToBeShown;
}
}
// I just remove the door since that is essentially what Monty Hall is doing when
// He reveals one of the goats
doors.RemoveAt(doorMontyOpens);
}
// Since player choice is always door #1 (index 0) and there are only two doors left,
// we only need to check door #2 at index 1. If it has the car, it is a win. If not, a loss.
// This simulation only tests the case in which the player changes doors after Monty reveals
// a door. So it SHOULD usually have about 667 wins and 333 losses. Why do I get 50/50???
if (doors[1].Contents == "car")
{
wins++;
}
else
{
losses++;
}
attempts++;
}
Console.WriteLine($"{wins}");
Console.WriteLine($"{losses}");
Console.WriteLine($"{attempts}");
public class Door
{
public string Contents { get; set; }
public bool Opened { get; set; }
public bool PlayerChoice { get; set; }
}