首頁 > 後端開發 > C++ > C#中如何有效率地找出數組元素的所有組合?

C#中如何有效率地找出數組元素的所有組合?

Linda Hamilton
發布: 2025-01-19 23:07:08
原創
651 人瀏覽過

How to Efficiently Find All Combinations of Array Elements in C#?

高效率找出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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板