2

As the title says, is there a way to loop the nesting of loops non-recursively? That is, let's say I wanted to do this:

while (condition)
{
    while (condition)
    {
         while (condition)
         {
             .... //<- more whiles
         }
     }
}

with 100 nested while loops. Is there a way to do this without hard-coding it and without using recursion?

Edit: Just to be clear, the 100 is meant for demonstrative purposes.

4

5 回答 5

0

我知道您特别说过no recursion,但我假设这是因为您希望能够在层次结构的下降过程中调用不同的函数/方法。

那么,如果您可以递归调用相同的函数,但让函数依次使用委托调用各种其他函数,那会怎样?是否可以传递要调用的委托函数列表,以及条件的另一个委托列表(是否继续循环)?

我只花了几分钟的时间,这是一种抽象的想法/思想实验,而不是具体的解决方案;我什至不确定这是否可能,但这应该显示基本概念:

public delegate void CallableFunctionDelegate();
public delegate bool CallableCondition();

public void CallDelegatesRecursively(
                        List<CallableFunctionDelegate> methodsToCall, 
                        List<CallableCondition> conditionsToCall){

    var currentDelegate = delegatesToCall[0];

    while(conditionsToCall()){

        currentDelegate();  // Call current function

        // (Verify that the list is not empty, etc...)

        var restOfList = methodsToCall.GetRange(1, methodsToCall.length);
        var restOfConditions = 
                   conditionsToCall.GetRange(1, conditionsToCall.length);

        // Call next function in the "hierarchy" / list:
        CallDelegatesRecursively(restOfList, restOfConditions);
    }
}

现在它应该(理论上!;))可以调用该函数,并将函数列表传递给它F,只要某些相应的条件C评估为真,每个函数都可以在 while 循环中调用。在每次调用 之后,还将调用F一些“子函数” (列表中的下一个)(但前提是它的相应条件在递归调用中计算为真......)。F2C2

于 2012-08-16T12:07:27.227 回答
0

如果你有 100 个嵌套循环,我认为你的算法可能有问题。

至少,您可以尝试使您的方法递归。像这样的东西(它可能会根据您实际尝试做的事情而大不相同):

private void RecursiveWhile(int nestedLevel)
{
    // some logic
    if (nestedLevel == 0)
    {
        // some logic
    }
    else
    {     
        // some logic, maybe a while
        RecursiveWhile(nestedLevel - 1);
        // some logic, maybe breaking out of the while
    }
}

例如,您将使用RecursiveWhile(100)100 个级别的 while。

但我非常鼓励您退后一步,思考您的算法以及为什么需要 100 级迭代。

于 2012-08-16T11:06:42.650 回答
0

由于没有其他任何事情发生:

while ({conditionA} && {conditionB} && {conditionC})
{
   /// ...
}

如果你有100,我怀疑你可能做错了什么。如果没有更多上下文,我们无法对此发表评论。

于 2012-08-16T10:31:45.363 回答
0

我不确定 100 个 while 循环是否有有效用例,但这里有。

我能想到的就是结合while条件。就像是:

while(x == 1)
{
    while(y == 2)
    {
    }
}

可能变成:

while(x == 1 && y == 2)
{
}

如果您的病情开始变得太长,我可能会将其提取到另一种方法中。

while(ShouldLoop(x, y))
{
}

private bool ShouldLoop(int x, int y)
{
    return x == 1 && y == 2;
}

当然,这只有在您没有在非嵌套循环中做任何工作时才有效。

于 2012-08-16T10:31:55.803 回答
0

您是否考虑过使用BitArray类?可以用作条件掩码,例如...

于 2012-08-16T10:55:21.147 回答