我想获得所有可能的重复组合列表。
例如
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/