0

I have three baskets of balls and each of them has 10 balls which have the following numbers:

Basket 1: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Basket 2: 11, 12, 13, 14, 15, 16, 17, 18, 19, 20

Basket 3: 21, 22, 23, 24, 25, 26, 27, 28, 29, 30

What would be the possible variations If I were to pick one ball from each basket? I guess this is called as Probability in Mathematics but not sure. How would you write this code in C# (or any other programming language) to get the correct results?

Edit:

Based on @Kilian Foth's comment, here is the solution in C#:

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> basket1 = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        IEnumerable<string> basket2 = new List<string> { "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
        IEnumerable<string> basket3 = new List<string> { "21", "22", "23", "24", "25", "26", "27", "28", "29", "30" };

        foreach (var item1 in basket1)
        foreach (var item2 in basket2)
        foreach (var item3 in basket3)
        {
            Console.WriteLine("{0}, {1}, {2}", item1, item2, item3);
        }

        Console.ReadLine();
    }
}
  • 3
    This has nothing to do with probability, it's just combinatorics. You get 10x10x10 possibilies, from (1,11,21) to (10,20,30). To enumerate them all you'll need a triply-nested loop. – Kilian Foth Feb 6 '14 at 10:02
  • @KilianFoth sweet, thanks! I guess the title of the question is also not right in this case. I edited the question. Put this as answer, I'll accept it. – tugberk Feb 6 '14 at 10:14
  • Probability would be to do with the likelihood of a given combination (or combinations) occurring. – Robbie Dee Feb 6 '14 at 11:15
  • 2
    More suited to codegolf.stackexchange.com ? – ozz Feb 6 '14 at 11:53
  • Judging by the question, I'm guessing that OP wants to be able to read and understand the answer ;) – Ampt Nov 3 '14 at 22:06
1

What you are looking for is called a Cartesian product (or sometimes cross product). One possible algorithm is nested loops, but there is an extensive literature on the subject. Don't reinvent the wheel.

There is also an extensive answer here: https://stackoverflow.com/questions/1741364/efficient-cartesian-product-algorithm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.