Generate combination using string array in c#

algorithm, arrays, c#, combinations

Solution

You could use a simple recursion:

private static IEnumerable<string> Combinations(int start, int level)
{
  for ( int i = start; i < array.Length; i++ )
    if ( level == 1 )
      yield return array[i];
    else
      foreach ( string combination in Combinations(i + 1, level - 1) )
        yield return String.Format("{0} {1}", array[i], combination);
}

The call it like this:

  var combinations = Combinations(0, 2);

  foreach ( var item in combinations )
    Console.WriteLine(item);

Problem

Possible Duplicate: Different combinations of an array (C#) ``` string[] array = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10"}; ``` How to generate to 2 / 3 / 4 / 5 strings per combination like for example 2 strings per combination, with no repeats/duplicates, disregard of position as well, using combination formula nCr = 10!/2!(10-2)! = 45 combinations. I need the output to be like this: ``` "01", "02" "01", "03" "01", "04" ... "02", "03" // eliminate the "02","01" 'cause it is same as "01","02" combination "02", "04" ... ``` Then to generate combinations of 3 strings, would have 120 combinations (according to nCr). I need the output to be like this: ``` "01","02","03" "01","02","04" ... ``` And combinations of 4 strings, would have 210 combinations, the least, combinations of 5 strings per combination, would have 252 combinations. How can I write that? I've used up many loops and it looks really a mess.

Original source

Related problems