Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace MontyHall
- {
- class Puzzle
- {
- private bool[] doors;
- public int[] unchosen (int choice)
- {
- int[] u = new int[2];
- for (int i = 0, iu = 0; i < 3; ++i) {
- if (choice != i)
- u [iu++] = i;
- }
- //Console.WriteLine ("\t <<unchosen returning {0} and {1}>>", u [0], u [1]);
- return u;
- }
- public int unchosen_loser(Random r, int choice)
- {
- int[] unch = unchosen (choice);
- int rand = r.Next (2);
- if (doors [unch [rand]] != true)
- return unch [rand];
- else
- {
- if (rand == 0)
- return unch[1];
- else
- return unch[0];
- }
- }
- public bool reveal(int choice)
- {
- return doors [choice];
- }
- public Puzzle(Random r)
- {
- doors = new bool[3];
- doors [r.Next (3)] = true;
- }
- }
- class MainClass
- {
- public static void Main (string[] args)
- {
- int iterations = 10000000;
- int choice;
- int successes = 0;
- int failures = 0;
- Random r = new Random();
- if (args.Length != 0)
- int.TryParse (args [0], out iterations);
- Console.WriteLine ("Testing Monte Hall problem {0} times...", iterations);
- r = new Random ();
- for (int i = 0; i < iterations; ++i)
- {
- Puzzle p = new Puzzle (r);
- choice = r.Next (3);
- int[] unch = p.unchosen (choice);
- int loser = p.unchosen_loser (r, choice);
- //int newchoice;
- //Console.WriteLine ("New puzzle!" + Environment.NewLine + "Choosing: {0}", choice + 1);
- //Console.WriteLine ("\t << Unchosen doors are {0} and {1}. >>", unch [0] + 1, unch [1] + 1);
- //Console.WriteLine ("Door {0} has been opened!", loser + 1);
- //Change this below to alter strategy
- if (unch [0] == loser)
- choice = unch [1];
- else
- choice = unch [0];
- //Console.WriteLine ("Changing choice to {0}.", choice + 1);
- if (p.reveal (choice) == true) {
- //Console.WriteLine ("You win!");
- ++successes;
- } else {
- //Console.WriteLine ("You lose.");
- ++failures;
- }
- for (int iw = 0; iw < 3; ++iw) {
- if (p.reveal (iw)) {
- //Console.WriteLine ("<< Winning door is {0}. >> ", iw + 1);
- }
- }
- //Console.WriteLine ();
- }
- Console.WriteLine ("Out of {0} games, you have won {1} ({2}%).", iterations, successes, ((double)successes / (double)iterations) * 100);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement