0

i have two numbers 1,2 in one array.Now i want to generate all the possible combinations of arrays(of size=5) like

1,2,0,0,0 || 2,1,0,0,0 || 1,0,2,0,0 . . . . .

I tried to write a recursive function but its not working

Now I want to solve this using LINQ because the code will be considerably small.

Please help me

Surya KLSV
  • 1,260
  • 4
  • 18
  • 26
  • By combination you mean permutations? – CodesInChaos Jan 07 '12 at 13:52
  • see [this question](http://stackoverflow.com/questions/774457/combination-generator-in-linq) or [this one](http://stackoverflow.com/questions/1119699/how-to-generate-combinations-of-elements-of-a-listt-in-net-4-0) – voidengine Jan 07 '12 at 13:53

2 Answers2

1

LINQ is excellent for searching; it's much worse at generating, so it is a wrong tool for the job. So is recursion (although it is a better choice than LINQ). What you need is two nested loops, like this:

var elements = new [] {1, 2};
for (var i = 0 ; i != 5 ; i++) {
    for (int j = 0 ; j != 5 ; j++) {
        if (i == j) continue;
        var data = new int[5];
        data[i] = elements[0];
        data[j] = elements[1];
        ProcessCombination(data);
    }
}

Here is what the code does: at each iteration of the inner loop it places the first and the second element from the elements array at distinct positions i and j. Nested loops go from 0 to 5, making sure all position combinations are covered.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
-1

You could use something like this:

  public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> list)
  {
            if (list.Count() == 1)
                return new List<IEnumerable<T>> { list };

            return list.Select((a, i1) => Permute(
                            list.Where((b, i2) => i2 != i1)).Select(
                                  b => (new List<T> { a }).Union(b))
                            ).SelectMany(c => c);
   };

.....

var result = Permute(new int[]{1,2,0,0,0});  
Mithrandir
  • 24,869
  • 6
  • 50
  • 66
  • -1 Besides not giving a reference to original code http://stackoverflow.com/a/5757434/932418', It doesn't work for `new int[]{1,2,0,0,0}` (`multiple 0s`) – L.B Jan 07 '12 at 15:07