Words combinations without repetition
What you are trying to do is get all the permutations of a collection.
- Unique permutations of list
- permutations of k objects from a set of n algorithm
Here is the code snippet:
static void Main(string[] args)
{
var list = new List<string> { "a", "b", "c", "d", "e" };
var result = GetPermutations(list, 3);
foreach (var perm in result)
{
foreach (var c in perm)
{
Console.Write(c + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> items, int count)
{
int i = 0;
foreach (var item in items)
{
if (count == 1)
yield return new T[] { item };
else
{
foreach (var result in GetPermutations(items.Skip(i + 1), count - 1))
yield return new T[] { item }.Concat(result);
}
++i;
}
}
Outputs:
a b c
a b d
a b e
a c d
a c e
a d e
b c d
b c e
b d e
c d e