Home >Backend Development >C++ >How to Efficiently Find All Combinations of Array Elements in C#?
Efficiently find all combinations of C# array elements
When working with array elements, it is useful to extract all possible combinations of elements. This task often appears in fields such as data analysis and combinatorial optimization.
Permutations and combinations of repeated elements
Suppose there is an array [1, 2, 3, 4]. To find all combinations of length 2 with repeated elements, you can use the following function:
<code class="language-csharp">static IEnumerable<IEnumerable<T>> GetPermutationsWithRept<T>(IEnumerable<T> list, int length) { if (length == 1) return list.Select(t => new T[1] { t }); return GetPermutationsWithRept(list, length - 1) .SelectMany(t => list, (t1, t2) => t1.Concat(new T[1] { t2 })); }</code>
This function considers combinations containing repeated elements, such as [1, 1], [1, 2], etc.
Permutation and combination (excluding repeated elements)
To exclude duplicate elements, use the GetPermutations
function:
<code class="language-csharp">static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length) { if (length == 1) return list.Select(t => new T[1] { t }); return GetPermutations(list, length - 1) .SelectMany(t => list.Where(o => !t.Contains(o)), (t1, t2) => t1.Concat(new T[1] { t2 })); }</code>
This function ensures combinations such as [1, 2], [1, 3] and [2, 3], but not [1, 1].
K combination with repeated elements
Consider finding combinations of length 2 with repeated elements, allowing multiple occurrences of the element:
<code class="language-csharp">static IEnumerable<IEnumerable<T>> GetKCombsWithRept<T>(IEnumerable<T> list, int length) where T : IComparable { if (length == 1) return list.Select(t => new T[1] { t }); return GetKCombsWithRept(list, length - 1) .SelectMany(t => list.Where(o => o.CompareTo(t.Last()) >= 0), (t1, t2) => t1.Concat(new T[1] { t2 })); }</code>
This function generates combinations such as [1, 1], [1, 2] and [2, 2].
K combination (excluding repeated elements)
For combinations without repeated elements:
<code class="language-csharp">static IEnumerable<IEnumerable<T>> GetKCombs<T>(IEnumerable<T> list, int length) where T : IComparable { if (length == 1) return list.Select(t => new T[1] { t }); return GetKCombs(list, length - 1) .SelectMany(t => list.Where(o => o.CompareTo(t.Last()) > 0), (t1, t2) => t1.Concat(new T[1] { t2 })); }</code>
This function generates combinations such as [1, 2], [1, 3] and [2, 3].
The above is the detailed content of How to Efficiently Find All Combinations of Array Elements in C#?. For more information, please follow other related articles on the PHP Chinese website!