Getting all the combinations in an array

Lets extend it, so maybe we can see the pattern:

string[] arr = new string[] { "A", "B", "C", "D", "E" };

//arr[0] + arr[1] = AB
//arr[0] + arr[2] = AC
//arr[0] + arr[3] = AD
//arr[0] + arr[4] = AE

//arr[1] + arr[2] = BC
//arr[1] + arr[3] = BD
//arr[1] + arr[4] = BE

//arr[2] + arr[3] = CD
//arr[2] + arr[4] = CE

//arr[3] + arr[4] = DE

I see two loops here.

  • The first (outer) loop goes from 0 to 4 (arr.Length - 1)
  • The second (inner) loop goes from the outer loops counter + 1 to 4 (arr.Length)

Now it should be easy to translate that to code!


These should give you a starting point:
http://www.interact-sw.co.uk/iangblog/2004/09/16/permuterate
http://www.codeproject.com/KB/recipes/Combinatorics.aspx


This code

var strs = new[] {"A", "B", "C", "D"};
var combinations = CreateCombinations(0, "", strs);
var text = string.Join(", ", combinations);

private List<string> CreateCombinations(int startIndex, string pair, string[] initialArray)
    {
        var combinations = new List<string>();
        for (int i = startIndex; i < initialArray.Length; i++)
        {
            var value = $"{pair}{initialArray[i]}";
            combinations.Add(value);
            combinations.AddRange(CreateCombinations(i + 1, value, initialArray));
        }

        return combinations;
    }

The text variable will contain

A, AB, ABC, ABCD, ABD, AC, ACD, AD, B, BC, BCD, BD, C, CD, D

Tags:

C#