Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Collections.Concurrent;
- using System.Threading;
- namespace Lind.MontyHall
- {
- class Program
- {
- protected static bool IsProcessing { get; set; }
- protected static ConcurrentQueue<ContestResult> Results { get; set; }
- protected static int Contests { get; set; }
- protected static int Winners { get; set; }
- protected static int Door1 { get; set; }
- protected static int Door2 { get; set; }
- protected static int Door3 { get; set; }
- static void Main(string[] args)
- {
- Results = new ConcurrentQueue<ContestResult>();
- IsProcessing = true;
- Task t = Task.Factory.StartNew(() => ProcessQueue());
- Parallel.For(0, 100000, contestNumber =>
- {
- Random random = new Random(contestNumber);
- int winningDoor;
- int[] doors = random.GetContest(out winningDoor);
- int contestentChoice = random.Next(0, doors.Length);
- int[] revealOptions = doors.Where(d => d != contestentChoice && d != winningDoor).ToArray();
- int revealDoor = random.GetRandomOrFirst(revealOptions);
- int finalChoice = doors.Where(d => d != contestentChoice && d != revealDoor).First();
- Results.Enqueue(new ContestResult(finalChoice == winningDoor, winningDoor));
- });
- IsProcessing = false;
- t.Wait();
- Console.WriteLine("Door1: " + Door1 + " Door2: " + Door2 + " Door3: " + Door3);
- Console.WriteLine("Switching door won " + Winners + "/" + Contests + " (" +
- ((double)Winners / Contests * 100) + "%)");
- }
- protected static void ProcessQueue()
- {
- while (IsProcessing || !Results.IsEmpty)
- {
- ContestResult result;
- if (!Results.IsEmpty && Results.TryDequeue(out result))
- {
- if (result.IsWinner)
- Winners++;
- switch (result.WinningDoor)
- {
- case 0: Door1++; break;
- case 1: Door2++; break;
- case 2: Door3++; break;
- }
- Contests++;
- }
- else if (Results.IsEmpty)
- Thread.Sleep(100);
- }
- }
- }
- public struct ContestResult
- {
- public ContestResult(bool isWinner, int door)
- {
- IsWinner = isWinner;
- WinningDoor = door;
- }
- public bool IsWinner;
- public int WinningDoor;
- }
- public static class Extensions
- {
- public static int GetRandomOrFirst(this Random random, int[] doors)
- {
- if (doors.Length == 1)
- return doors.First();
- return doors[random.Next(0, doors.Length)];
- }
- public static int[] GetContest(this Random random, out int winningDoor, int doorCount = 3)
- {
- List<int> doors = new List<int>();
- int i = 0;
- while (i < doorCount)
- {
- doors.Add(i);
- i++;
- }
- winningDoor = random.Next(0, doorCount);
- return doors.ToArray();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement