tags:

views:

118

answers:

2

I have to trace all outcome When tossing four coins at once

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());
    }
}

}

The output was

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

What went wrong ?

+11  A: 

You're selecting the arrays, you should be selecting first, second...

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


BTW you don't need to create different identical coins, you can toss the same coin several times:

        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
Motti
This is an additional question ,during selection i wish to omit {Head,Head,Head,Head} and {Tail,Tail,Tail,Tail} how is it possible?
Isuru
`where first != second || second != third || third != fourth`
sixlettervariables
+6  A: 

As Motti said, you're selecting the wrong thing. However, I'd like to point out that this can be simplified, as you only need one array, and you don't need an anonymous type:

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);
    }
}

To answer the comment, to exclude HHHH and TTTT you want something like:

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);
    }
}
Jon Skeet
Saw your answer after my edit (great minds and all that (no plagiarism here, no sirree)).
Motti
As motti said i hope even single coin is enough ,still do i need to go for array sides?
Isuru
sorry you are right ! I got it Mr Jon.
Isuru
This is an additional question ,during selection i wish to omit {Head,Head,Head,Head} and {Tail,Tail,Tail,Tail} how is it possible?
Isuru