话说昨天一篇文章《戏谈一道面试题》上了评论头条,地址如下http://www.cnblogs.com/haolujun/archive/2012/10/20/2731903.html。
该面试题是一个经典的数据概率问题,而既然是程序员,当然得有程序员的解决方案:用程序来描述业务,然后通过计算机做计算来算出所要的结果。
代码如下:
View Code
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int count = 0; int aobamaWinCount = 0; int luomuniWinCount = 0; while (true) { Random r = new Random(unchecked((int)(DateTime.Now.Ticks))); Dictionary<string, string> dcPeople = new Dictionary<string, string>(); dcPeople.Add("奥巴马", ""); dcPeople.Add("罗姆尼", ""); Dictionary<string, string> dcBox = new Dictionary<string, string>(); dcBox.Add("A", "狗屎"); dcBox.Add("B", "狗屎"); dcBox.Add("C", "狗屎"); int treasure_int = r.Next(1, 4); switch (treasure_int) { case 1: dcBox["A"] = "宝物"; break; case 2: dcBox["B"] = "宝物"; break; case 3: dcBox["C"] = "宝物"; break; default: break; } System.Threading.Thread.Sleep(50); //第一次奥巴马选择 int choose_aobama_int = r.Next(1, 4); switch (choose_aobama_int) { case 1: dcPeople["奥巴马"] = "A"; break; case 2: dcPeople["奥巴马"] = "B"; break; case 3: dcPeople["奥巴马"] = "C"; break; default: break; } string theShit = ""; //确定是狗屎的盒子 //罗姆尼选择去掉一坨狗屎,这里有两种情况,第一,奥巴马没猜到狗屎 第二:踩到了 //奥巴马踩到狗屎了 if (dcBox[dcPeople["奥巴马"]] == "狗屎") { foreach (var item in dcBox) { if (item.Value == "狗屎") { theShit = item.Key; } } } else { List<string> abcBox = new List<string>(); abcBox.Add("A"); abcBox.Add("B"); abcBox.Add("C"); abcBox.Remove(dcPeople["奥巴马"]); //在剩下的两个盒子中随机选择一个标记为狗屎 int shit_int = r.Next(0, 2); theShit = abcBox[shit_int]; } //接下来是罗姆尼选择 if (dcBox[dcPeople["奥巴马"]] == "狗屎")//如果奥巴马选择了狗屎,那么罗姆尼肯定知道剩下的哪个是宝物,肯定能选对宝物 { foreach (var item in dcBox) { if (item.Value == "宝物") { dcPeople["罗姆尼"] = item.Key; } } } else//如果奥巴马选中了宝物,那罗姆尼就只能在剩下的两个随机选取了 { int choose_luomuni_int = r.Next(0, 2); List<string> abcBox = new List<string>(); abcBox.Add("A"); abcBox.Add("B"); abcBox.Add("C"); abcBox.Remove(dcPeople["奥巴马"]); dcPeople["罗姆尼"] = abcBox[choose_luomuni_int]; } Console.WriteLine(); Console.WriteLine("-----------------------本轮抽奖结果---------------------------"); Console.WriteLine("奥巴马:抽到【" + dcBox[dcPeople["奥巴马"]] + "】"); Console.WriteLine("罗姆尼:抽到【" + dcBox[dcPeople["罗姆尼"]] + "】"); if (dcBox[dcPeople["奥巴马"]] == "宝物") { aobamaWinCount = aobamaWinCount + 1; } else { luomuniWinCount = luomuniWinCount + 1; } count++; if (count == 900) { Console.WriteLine("游戏结束"); Console.WriteLine("游戏一共进行了"+count+"次"); Console.WriteLine("奥巴马抽到宝物" + aobamaWinCount + "次"); Console.WriteLine("罗姆尼抽到宝物" + luomuniWinCount + "次"); Console.Read(); break; } } } } }
各位新建一个控制台程序,然后复制代码过去,按F5,耐心等候45秒,就会告诉你结果。
代码是临时写的,包括命名或者某些方面不足敬请谅解。