Search code examples
c#pseudocode

Finding all combinations, pseudo


I have 10 rows, each row can have 1-10 numbers with a value of 1-100 (the actual value doesn't really matter). As an example, the first three rows will look like:

1. (2 numbers)                         1st 2nd 1st 2nd
2. (1 number)   all combinations --->  1st 1st 1st 1st
3. (2 numbers)                         1st 1st 2nd 2nd

With real numbers:

1. 5, 7                                5   7  5  7
2. 2            all combinations --->  2   2  2  2
3. 12, 24                              12 12 24 24

This results in a total of 4 unique combinations.

How can this be solved? I've tried for-loops and if statements, but it simply won't work as it should.


Solution

  • Eric Lippert wrote a fantastic article on how to write a method that can take any number of sequences, each of an arbitrary size, and find the Cartesian Product (that's the technical term for what you're asking for) of all of those sequences in C# .

    This is a link to that article

    The code that he derives at the end of the article is as follows, although I highly suggest reading the article to see how he ended up there:

    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) 
    { 
      IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
      return sequences.Aggregate( 
        emptyProduct, 
        (accumulator, sequence) => 
          from accseq in accumulator 
          from item in sequence 
          select accseq.Concat(new[] {item})); 
    }
    

    Simple example usage:

    var array = new string[][] { new[] { "a", "b" }, new[] { "1", "2" } };
    foreach (var product in array.CartesianProduct())
        Console.WriteLine(string.Join(" ", product));