Create unique doubles and triplets from the collection

I have a collection of ( List ) elements ( String ). The number of items in this collection will always be between 0 and 9.

I need to create all combinations of pairs and triples from this collection. The item’s position in double or triplet does not matter. So, {1,2} equals {2,1} .

How can i achieve this? Maybe there is a good way to do this through LINQ?

+6
source share
1 answer

In the code below, I generate all unique doubles and triplets using linq. I use the fact that the strings are in full order.

This generates all duplicates:

 string[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" }; var combinations = from a in items from b in items where a.CompareTo(b) < 0 orderby a, b select new { A = a, B = b }; foreach(var pair in combinations) Console.WriteLine("({0}, {1})", pair.A, pair.B); 

This generates all triplets:

 string[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" }; var combinations = from a in items from b in items from c in items where a.CompareTo(b) < 0 && b.CompareTo(c) < 0 orderby a, b, c select new { A = a, B = b, C = c }; foreach(var triplet in combinations) Console.WriteLine("({0}, {1}, {2})", triplet.A, triplet.B, triplet.C); 

Update . There is a general solution to create all unique subsets of a certain length and still use linq. However, you need a return type, which may contain a subset. I created a simple LinkedNode class because it seems to me the most natural when combined with linq:

 void Main() { string[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" }; foreach(var combination in CreateCombinations(items, 5)) Console.WriteLine("({0})", combination.ToString()); } private static IEnumerable<LinkedNode> CreateCombinations(string[] items, int length) { if(length == 1) return items.Select(item => new LinkedNode { Value = item, Next = null }); return from a in items from b in CreateCombinations(items, length - 1) where a.CompareTo(b.Value) < 0 orderby a, b.Value select new LinkedNode<T> { Value = a, Next = b }; } public class LinkedNode { public string Value { get; set; } public LinkedNode Next { get; set; } public override string ToString() { return (this.Next == null) ? Value : Value + ", " + Next.ToString(); } } 

In the LinkedNode class, LinkedNode should be easy to implement an IEnumerable<string> or else convert LinkedNodes to List<string> or HashSet<string> . Note that you can remove the orderby a, b.Value if the order is not important.

+9
source

Source: https://habr.com/ru/post/901941/


All Articles