0

I am looking for the best way to get all possible int arrays of length n from int array of length k, including an option for n-1 items to be null. for example I have the array with 5 elements (k=5) and I want all combinations of 3 (n=3)

int[] numbers = new int[5] {1, 2, 3, 4, 5};

and the possible sub arrays of length 3:

{1,null,null},{1,null,2},{1,2,null}..... and so on.

What would be the best way to do it? Matan

Matan Kadosh
  • 1,669
  • 3
  • 18
  • 24
  • I am currently clueless about that, trying to get as much information from the internet about the best way to handle that. I found some good algorithms but it do not include the null possibilities. – Matan Kadosh Jan 24 '16 at 11:23
  • Take a look at this solution: http://stackoverflow.com/a/10630026. It will give you all the permutations, without the `null` values. In the example, replace `Enumerable.Range(1, 3)` with your `numbers` variable. – Serge Jan 24 '16 at 11:23
  • Thanks that's good, but i the null options are required in my need – Matan Kadosh Jan 24 '16 at 11:33

1 Answers1

0

You could include null in your numbers array. This code produces all possible permutations except of {null, null, null}.

var numbers = new int?[]{null, 1, 2, 3, 4, 5};
var result = new List<int?[]>();

foreach (int? x in numbers)
{
    foreach (int? y in numbers)
    {
        foreach (int? z in numbers)
        {
            if (x == null && y == null && z == null)
                continue;

            result.Add(new int?[] { x, y, z });
            Console.WriteLine("x: {0} - y: {1} - z: {2}", x, y, z);
        }
    }
}
kogelnikp
  • 447
  • 7
  • 11