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();
    }
}
6
  • 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. Commented Feb 6, 2014 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
    Commented Feb 6, 2014 at 10:14
  • Probability would be to do with the likelihood of a given combination (or combinations) occurring.
    – Robbie Dee
    Commented Feb 6, 2014 at 11:15
  • 2
    More suited to codegolf.stackexchange.com ?
    – ozz
    Commented Feb 6, 2014 at 11:53
  • Judging by the question, I'm guessing that OP wants to be able to read and understand the answer ;)
    – Ampt
    Commented Nov 3, 2014 at 22:06

1 Answer 1

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 and acknowledge you have read our privacy policy.

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