1

If N is fixed,like N = 3, then it is easy, i can use nested loops of depth 3. e.g.

from i in Enumerable.Range(0, 2)
from j in Enumerable.Range(0, 2)
from k in Enumerable.Range(0, 2)
select new int[] { i, j, k };

what if N is a variable?

Steven
  • 166,672
  • 24
  • 332
  • 435
colinfang
  • 20,909
  • 19
  • 90
  • 173
  • 1
    Duplicate: http://stackoverflow.com/q/3428870/21727 – mbeckish Nov 02 '11 at 13:02
  • The part I don't like is you end up with an array of variable dimension. Are you really sure that's what you want? – Tipx Nov 02 '11 at 13:07
  • @Tipx - I think the intention is to generate a collection of N element arrays, which is what the example does. – mbeckish Nov 02 '11 at 13:23
  • 1
    possible duplicate of [Cartesian Product of multiple array](http://stackoverflow.com/questions/7945555/cartesian-product-of-multiple-array) – Saeed Amiri Nov 02 '11 at 13:28

1 Answers1

0

What you need is some sort of array 'multiplyer'. Something like this:

private static IEnumerable<int[]> Multiply(IEnumerable<int[]> input,
    IEnumerable<int> multiplyers)
{
    foreach (var array in input)
    {
        foreach (var multiplyer in multiplyers)
        {
            yield return array.Concat(new int[] { multiplyer })
                .ToArray();
        }
    }
}

You can use this method as follows to get the same result as your example above:

int n = 3;

var multiplyers = Enumerable.Range(0, 2);

IEnumerable<int[]> results = 
    from m in multiplyers select new int[] { m };

while (n-- > 1)
{
    results = Multiply(results, multiplyers);
}

Now n is variable.

Steven
  • 166,672
  • 24
  • 332
  • 435