Word combinations without repetition

I have 10 words. How can I get all possible combinations of 5 words (n=10, k=5) . Order doesn't matter .

For example: "A", "B", "C", if k=2 (n=3 in this case) , he would like to use AB, BC and AC. Perhaps you know some useful code or example.

PS Sorry if I'm not right enough because I don't know English very well.

+6
string c # combinations words
source share
2 answers

What you are trying to do is get all the permutations of the collection.

  • Unique list permutations
  • permutation of k objects from a set of n algorithms

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:

 abcabdabeacdaceadebcd bcebdecde 
+15
source share

How about a more functional solution

 var list = new List<string> { "a", "b", "c", "d", "e" }; GetAllCombinations(list).OrderBy(_ => _).ToList().ForEach(Console.WriteLine); static IEnumerable<string> GetAllCombinations(IEnumerable<string> list) { return list.SelectMany(mainItem => list.Where(otherItem => !otherItem.Equals(mainItem)) .Select(otherItem => mainItem + otherItem)); } 

Ouput:

 ab ac ad ae ba bc bd be ca cb cd ce da db dc de ea eb ec ed 
0
source share

All Articles