using System;
using System.Collections.Generic;
using System.Linq;
namespace ThreeDoors
{
class Program
{
static void Main(string[] args)
{
List<Game> test = new List<Game>();
for (int i = 0; i < 1000; i++)
{
Game g = new Game();
Console.WriteLine(
"NO:{0:000} 汽車:{1} 初選:{2} 主持人:{3} 更換:{4} " +
"不換結果:{5} 更換結果:{6}",
i, g.WinIndex, g.PlayerPick, g.HostPick, g.ChangePick,
g.ResultWhenNoChange, g.ResultWhenChange);
test.Add(g);
}
Console.WriteLine("不換而嬴得汽車的次數: {0}",
test.Where(g => g.ResultWhenNoChange == "Car").Count());
Console.WriteLine("更換後嬴得汽車的次數: {0}",
test.Where(g => g.ResultWhenChange == "Car").Count());
Console.Read();
}
}
public class Game
{
class Door
{
public int Index;
public string Result;
public Door(int idx, string result) {
Index = idx;
Result= result;
}
}
//門的編號為0, 1, 2
List<Door> Doors =
new List<Door>()
{
new Door(0, "Goat"), new Door(1, "Goat"),
new Door(2, "Goat")
};
//汽車所在門的編號
public int WinIndex = -1;
//使用者初選編號
public int PlayerPick = -1;
//更換選擇後的編號
public int ChangePick = -1;
//主持人選取的山羊門編號
public int HostPick = -1;
//更換選擇的結果
public string ResultWhenChange
{
get
{
return Doors
.Single(o => o.Index == ChangePick).Result;
}
}
//維持原來選擇的結果
public string ResultWhenNoChange
{
get
{
return Doors
.Single(o => o.Index == PlayerPick).Result;
}
}
static Random rnd = new Random();
public Game()
{
//亂數選一個門放汽車
WinIndex = rnd.Next(3);
Doors.Single(o => o.Index == WinIndex)
.Result = "Car";
//參賽者挑一個門
PlayerPick = rnd.Next(3);
//主持人挑山羊門
//若參賽者未挑中汽車
if (PlayerPick != WinIndex)
{
//找出參賽者未選的另一集山羊
HostPick = Doors.Single(o =>
o.Index != PlayerPick &&
o.Result == "Goat").Index;
}
else //參賽者挑中汽車
{
HostPick =
Doors.Where(o => o.Result == "Goat")
//挑過零個或一個隨機選羊
.Skip(rnd.Next(2)).First().Index;
}
//PlayerPick與HostPick以外的就是結果
ChangePick = Doors.Single(o =>
o.Index != PlayerPick &&
o.Index != HostPick).Index;
}
}
}