高效率找出C#陣列元素的所有組合
在處理陣列元素時,提取所有可能的元素組合非常有用。這項任務經常出現在數據分析、組合優化等領域。
含重複元素的排列組合
假設有一個陣列 [1, 2, 3, 4]。若要找出長度為 2 的所有含重複元素的組合,可以使用下列函數:
<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>
此函數考慮包含重複元素的組合,例如 [1, 1]、[1, 2] 等。
排列組合(不含重複元素)
要排除重複元素,請使用 GetPermutations
函數:
<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>
此函數確保組合例如 [1, 2]、[1, 3] 和 [2, 3],但不包含 [1, 1]。
含重複元素的K組合
考慮找出長度為 2 的含重複元素的組合,允許元素多次出現:
<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>
此函數產生組合,例如 [1, 1]、[1, 2] 和 [2, 2]。
K組合(不含重複元素)
對於不含重複元素的組合:
<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>
此函數產生組合,例如 [1, 2]、[1, 3] 和 [2, 3]。
以上是C#中如何有效率地找出數組元素的所有組合?的詳細內容。更多資訊請關注PHP中文網其他相關文章!