0

I'm trying to write a method that enumerates all sequences that can be used in a for loop.

Assume IEnumerable<int>[] intValues is the original collection if integers and let's say it is:

intValues[0] = int[] {1, 2, 3}
intValues[1] = int[] {4, 5}

I need to write EnumerateSequences(...) such that:

foreach (int[] seq in EnumerateSequences(...))
{
    // 1st iteration: seq = [1, 4]
    // 2nd iteration: seq = [1, 5]
    // 3rd iteration: seq = [2, 4]
    // 4th iteration: seq = [2, 5]
    // 5th iteration: seq = [3, 4]
    // 6th iteration: seq = [3, 5]
}

I came up with this method, however, EnumerateSequences(intValues, 0, null) won't recurse inside so it always returns null:

private static IEnumerable<int[]> EnumerateSequences(IEnumerable<int>[] intValues, int pos, int[] seq) 
{
    if (pos < intValues.Length)
    {
        foreach (var f in intValues[pos])
        {
            if (seq == null && pos == 0)
            {
                seq = new int[intValues.Length];
            }
            seq[pos] = f;
            var _ = EnumerateSequences(intValues, pos + 1, seq);
        }
    }
    else if (pos == intValues.Length || seq == null)
    {
        yield return seq;
    }
}
Mahmoud
  • 51
  • 3
  • 1
    Nothing could be easier than "enumerating a sequence" (be it an array, a List , an enum - whatever) in C#. Q: What exactly are you trying to do, such that you need "recursion" (or some other over-complicated solution)??? – paulsm4 Oct 19 '20 at 17:55
  • The reason I was using recursion is the size of `IEnumerable[] intValues` is not known prior. The enumeration would be equivalent of a nested for loop, otherwise. – Mahmoud Oct 19 '20 at 17:59
  • 1
    The example shown in the post is not "sequence of unknown size" (as number of combinations is known). Are you sure title matches the problem? (so far it indeed looks like duplicate of "get all combinations" despite unrelated title). – Alexei Levenkov Oct 19 '20 at 18:07
  • @AlexeiLevenkov They just mean unknown at compile time, so you can't do `from a in first from b in second from c in third select (a,b,c);` – Servy Oct 19 '20 at 18:14
  • 2
    What you're looking for is the Cartesian product and Eric Lippert has a blog post about it https://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/ – juharr Oct 19 '20 at 18:35
  • 1
    Servy's [duplicate](https://stackoverflow.com/questions/3093622/) and Juharr's [link](https://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/) are spot-on. The original question, as posed, is a great example of an [XY Problem](https://en.wikipedia.org/wiki/XY_problem) – paulsm4 Oct 19 '20 at 20:26

0 Answers0