Generate all combinations of a sequence
I was after an algorithm that could product every combination of a string of characters.
Ofcourse I could have written my own... but I knew that someone would have already had something.
"This is a simple C# algorithm that takes a sequence of characters and returns every possible combination of those characters."
class Program
{
static void Main(string[] args)
{
var items = "ABCDEF";
var combinations = GetCombinations(items)
.Where(x => x.Length == items.Length)
.ToList();
foreach (var combination in combinations)
{
Console.WriteLine(combination);
}
Console.WriteLine($"Item count: {combinations.Count}");
Console.WriteLine($"Distinct count: {combinations.Distinct().Count()}");
Console.Read();
}
private static IEnumerable<string> GetCombinations(IEnumerable<char> items)
{
var combinations = new List<string> { string.Empty };
foreach (var item in items)
{
var newCombinations = new List<string>();
foreach (var combination in combinations)
{
for (var i = 0; i <= combination.Length; i++)
{
newCombinations.Add(
combination.Substring(0, i) +
item +
combination.Substring(i));
}
}
combinations.AddRange(newCombinations);
}
return combinations;
}
}
Reference: Appetere article by Steve Moss