gpt4 book ai didi

C# - 遍历多个数组/列表的最有效方法

转载 作者:行者123 更新时间:2023-12-02 05:22:24 25 4
gpt4 key购买 nike

我有五个不同长度的数组,我需要遍历所有数组以生成所有可能的内容组合。我目前正在使用 5 个嵌套的 for 循环,如下所示:

for (int a = 1; a < Array1.Length - 1; a++)
{
for (int b = 1; b < Array2.Length - 1; b++)
{
for (int c = 1; c < Array3.Length - 1; c++)
{
for (int d = 1; d < Array4.Length - 1; d++)
{
for (int e = 1; e < Array5.Length - 1; e++)
{
//do something
}
}
}
}
}

由于数组的大小,我最终得到了超过 4.56 亿次迭代。总的来说,我对编程很陌生,特别是 C#。我只是好奇是否有更有效的方法来完成此任务。

谢谢。

最佳答案

你经历了那么多迭代,因为有那么多组合:这叫做 combinatorial explosion .如果您必须遍历所有可能的组合,您就无法更有效地做到这一点。

您可以通过使用递归,使用更少的代码行或无需对数组数量(在您的情况下为五个)进行硬编码来对其进行编码。但是,迭代次数不会改变,只会改变代码行数。

void processCombination(int[] combination) {
// combination[i] has the index of array #i
...
}
void combine(int p, int[] indexes, int[] sizes) {
if (p == indexes.Length) {
processCombination(indexes);
} else {
for (indexes[p] = 0 ; indexes[p] != sizes[p] ; indexes[p]++) {
combine(p+1, indexes, sizes);
}
}
}

关于C# - 遍历多个数组/列表的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13655299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com