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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With