I have 10 words. How can I get all possible combinations of 5 words (n=10, k=5). The order does not matter.
For example: \"A\",
What you are trying to do is get all the permutations of a collection.
Here is the code snippet:
static void Main(string[] args)
{
var list = new List { "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> GetPermutations(IEnumerable 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