Unique Combinations
This algorithm finds all unique combinations in a specified list of values.
public static List<List<string>> GenerateCombinations(string[] arr)
{
List<List<string>> combinations = new List<List<string>>();
int length = arr.Length;
for (int i = 0; i < (1 << length); ++i)
{
List<string> combination = new List<string>();
int count = 0;
for (count = 0; count < length; ++count)
{
if ((i & 1 << count) > 0)
combination.Add(arr[count]);
}
if (count > 0 && combination.Count > 0)
combinations.Add(combination);
}
return combinations;
}
Example
string[] arr = { "How", "Are", "You" };
List<List<string>> combinations = GenerateCombinations(arr);
Output
{"How"}
{"Are"}
{"How", "Are"}
{"You"}
{"How", "You"}
{"Are", "You"}
{"How", "Are", "You"}