Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all the combinations in an array

Tags:

c#

Say I have the following array:

var arr = new[] { "A", "B", "C" };

How can I produce all the possible combinations that contain only two characters and no two the same (e.g. AB would be the same as BA). For example, using the above array it would produce:

AB
AC
BC

Please note that this example has been simplified. The array and the length of the string required will be greater.

I'd really appreciate if someone could help.

like image 853
nfplee Avatar asked Aug 13 '09 15:08

nfplee


People also ask

How do you find all permutations of an array?

You take first element of an array (k=0) and exchange it with any element (i) of the array. Then you recursively apply permutation on array starting with second element. This way you get all permutations starting with i-th element.


1 Answers

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
like image 127
Yurii Avatar answered Oct 28 '22 14:10

Yurii