C#的可能结果

时间:2009-10-18 15:30:46

标签: c# probability

我必须追踪所有结果一次抛出四个硬币

public void TossCoin()
{
    var coin1 = new string[]{ "Head", "Tail" };
    var coin2 =new string[] { "Head", "Tail" };
    var coin3 =new string[] { "Head", "Tail" };
    var coin4 =new string[] { "Head", "Tail" };
    var outcome =from first in coin1 
                 from second in coin2
                 from third in coin3
                 from fourth in coin4 
                 select new {possibility= coin1+","+coin2+","+coin3+","+coin4};

    foreach (var oc in outcome)
    {
        Console.WriteLine(oc.possibility.ToString());
    }
}

}

输出

System.String [],...............

出了什么问题?

2 个答案:

答案 0 :(得分:11)

您正在选择数组,您应该选择firstsecond ...

select new { possibility = first + "," + second + "," + third + "," + fourth };

你不需要制作不同的相同硬币,你可以多次掷同一枚硬币:

        var coin = new string[] { "Head", "Tail" };
        var outcome =
             from first in coin
             from second in coin
             from third in coin
             from fourth in coin
             select new { possibility = first + "," + second + "," + third + "," + fourth 

答案 1 :(得分:6)

正如Motti所说,你选错了。但是,我想指出这可以简化,因为你只需要一个数组,而且你不需要匿名类型:

public void TossCoin()
{
    string[] sides = { "Head", "Tail" };
    var outcome = from first in sides 
                  from second in sides
                  from third in sides
                  from fourth in sides 
                  select first + "," + second + "," + third + "," + fourth;

    foreach (string oc in outcome)
    {
        Console.WriteLine(oc);
    }
}

要回答评论,要排除HHHH和TTTT,您需要以下内容:

public void TossCoin()
{
    string[] sides = { "Head", "Tail" };
    var outcome = from first in sides 
                  from second in sides
                  from third in sides
                  from fourth in sides
                  where !(first == second && second == third && third == fourth)
                  select first + "," + second + "," + third + "," + fourth;

    foreach (string oc in outcome)
    {
        Console.WriteLine(oc);
    }
}