c# - 重复获取 k 个元素的所有组合

标签 c# combinations

我想获得所有可能的重复组合列表。

例如

Input: 1,2,3 
Result: 111,112,...,332,333

为此我使用 this修改后的方法运行良好

public static IEnumerable<IEnumerable<T>> CombinationsWithRepeat<T>(this IEnumerable<T> elements, int k)
{
    return k == 0 ? new[] { new T[0] } : elements.SelectMany((e, i) => elements.CombinationsWithRepeat(k - 1).Select(c => (new[] { e }).Concat(c)));
}

我的问题是这种递归方法的内存使用。输入 60 个元素且 K = 4 时,已经出现了 Out Of Memory Exception

我需要在 K = 10 的情况下运行它。

问题:有没有简单的方法可以避免这个异常?我需要迭代方法吗?

更新:

引用 Corak 的评论 - K 必须是动态的

这应该适用于 60 个元素和 K = 10 但它不是动态的。

StreamWriter sr = new StreamWriter(@"c:\temp.dat");
List<char> cList = new List<char>() { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
for (int i = 0; i < cList.Count; i++)
    for (int j = 0; j < cList.Count; j++)
        for (int k = 0; k < cList.Count; k++)
            sr.WriteLine(cList[i] + cList[j] + cList[k]);

最佳答案

给你:

    const int SelectionSize = 4;

    private static long _variationsCount = 0;
    private static int[] _objects;
    private static int[] _arr;

    static void Main(string[] args)
    {
        _objects = new int[]{1,2,3,4,5,6,7,8,9,10};
        _arr = new int[SelectionSize];

        GenerateVariations(0);
        Console.WriteLine("Total variations: {0}", _variationsCount);
    }

    static void GenerateVariations(int index)
    {
        if (index >= SelectionSize)
            Print();
        else
            for (int i = 0; i < _objects.Length; i++)
            {
                _arr[index] = i;
                GenerateVariations(index + 1);
            }
    }

    private static void Print()
    {
        //foreach (int pos in arr)
        //{
        //    Console.Write(objects[pos] + " ");
        //}
        //Console.WriteLine();
        _variationsCount++;
    }

即使选择大小为 10,它也能正常工作(大约需要 2 分钟)。但请记住,控制台打印速度非常慢,这就是我将其注释掉的原因。如果你想打印列表,你可以使用 stringbuilder 并且只在程序完成时打印。

关于c# - 重复获取 k 个元素的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31668781/

相关文章:

c++ - 在 C++ 中创建 n 个项目的所有可能的 k 个组合

javascript - 制作 1 和 0 的所有组合。代码在 java 中运行良好但在 js 中运行不佳

c# - 我是否应该断言在给定方法的每个单元测试中都会调用依赖项的方法?

c# - Web API HttpResponseMessage 内容返回不完整

c# - wpf GUI线程中的线程太慢

c# - app.config 分离实现

elasticsearch 标记为单词对

c# - 如何在 C# 中创建一个包以在 IronPython 中使用

c# - 如何获得子集的所有可能组合?

c++ - 根据位置计算组合