如何生成列表元素的组合<T>在 .NET 4.0 中 [英] How to Generate Combinations of Elements of a List<T> in .NET 4.0

查看:25
本文介绍了如何生成列表元素的组合<T>在 .NET 4.0 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与回答的问题相似但不完全相同的问题 此处.

I have a question that is similar, but not identical, to the one answered here.

我想要一个函数从 n 个元素的列表中生成所有 k 元素的组合.请注意,我正在寻找组合,而不是排列,并且我们需要一个解决方案来改变 k(即,对循环进行硬编码是不行的).

I would like a function generate all of the k-combinations of elements from a List of n elements. Note that I am looking for combinations, not permutations, and that we need a solution for varying k (i.e., hard-coding the loops is a no-no).

我正在寻找一种解决方案,a) 优雅,b) 可以在 VB10/.Net 4.0 中编码.

I am looking for a solution that is a) elegant, and b) can be coded in VB10/.Net 4.0.

这意味着 a) 需要 LINQ 的解决方案是可以的,b) 那些使用 C#yield"命令的不是.

This means a) solutions requiring LINQ are ok, b) those using the C# "yield" command are not.

组合的顺序并不重要(即字典序、格雷码、你有什么),如果两者发生冲突,则优雅优先于性能.

The order of the combinations is not important (i.e., lexicographical, Gray-code, what-have-you) and elegance is favored over performance, if the two are in conflict.

(OCaml 和 C# 解决方案此处 将是完美的,如果它们可以在 VB10 中编码.)

(The OCaml and C# solutions here would be perfect, if they could be coded in VB10.)

推荐答案

在 C# 中生成组合列表作为 k 个元素的数组的代码:

Code in C# that produces list of combinations as arrays of k elements:

public static class ListExtensions
{
    public static IEnumerable<T[]> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        List<T[]> result = new List<T[]>();

        if (k == 0)
        {
            // single combination: empty set
            result.Add(new T[0]);
        }
        else
        {
            int current = 1;
            foreach (T element in elements)
            {
                // combine each element with (k - 1)-combinations of subsequent elements
                result.AddRange(elements
                    .Skip(current++)
                    .Combinations(k - 1)
                    .Select(combination => (new T[] { element }).Concat(combination).ToArray())
                    );
            }
        }

        return result;
    }
}

此处使用的集合初始值设定项语法在 VB 2010 中可用 (来源).

Collection initializer syntax used here is available in VB 2010 (source).

这篇关于如何生成列表元素的组合&lt;T&gt;在 .NET 4.0 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆