2013-02-20 38 views
2

在Java中,我有整數d等於2, 3, 4, ..., dmax以下一般代碼 - 高達最大數目dmax : d < dmax(因此該代碼是在該範圍內重複的d每個值):系列嵌套循環的且無需遞歸

// d is the number of wrapper loops 
int[] ls = new int[d]; 
... 
// let ls array be filled with some arbitrary positive numbers here 
... 
// first wrapper loop 
for (int i1 = 0; i1 < ls[0]; i1++) { 

    ... 

     // last wrapper loop 
     for (int id = 0; id < ls[d - 1]; id++) { 

      // internal loop 
      for (int j = id + 1; j < ls[d - 1]; j++) { 

       myCode(); 

      } 

     } 

    ... 

} 

d = 3情況下,它看起來像:

int ls = new int[3]; 
ls[0] = 5; ls[1] = 7; ls[2] = 5; 

for (int i1 = 0; i1 < ls[0]; i1++) { 

    for (int i2 = 0; i2 < ls[1]; i2++) { 

     for (int i3 = 0; i3 < ls[2]; i3++) { 

      for (int j = i3 + 1; j < ls[2]; j++) { 

       myCode(); 

      } 

     } 

    } 

} 

我要收集所有重複的代碼到一個單一的廣義之一。爲了這個目的,我可以使用while循環和遞歸象下面這樣:

int d = 2, dmax = 10; 
while (d < dmax) { 
    // in algorithm ls is pre-filled, here its length is shown for clearance 
    int[] ls = new int[d]; 
    for (int i = 0; i < ls[0]; i++) { 
     doRecursiveLoop(1, d, -1, ls); 
    } 
    d++; 
} 

doRecursiveLoop(int c, int d, int index, int[] ls) { 

    if (c < d) { 
     for (int i = 0; i < ls[c]; i++) { 
      // only on the last call we give the correct index, otherwise -1 
      if (c == d - 1) index = i; 
      doRecursiveLoop(c + 1, d, index, ls); 
     } 
    } else { 
     for (int j = index + 1; j < ls[d - 1]; j++) { 

      myCode(); 

     } 
    } 

} 

任何人能提供一些線索,以動態地發生,而不遞歸嵌套循環我將如何處理這個問題?

+0

的可能的複製[C++:嵌套for循環(沒有遞歸)的動態數](http://stackoverflow.com/questions/ 18732974/c-dynamic-number-of-nested-for-loops-without-recursion) – 2016-04-20 08:25:03

+0

答案#1:http://stackoverflow.com/a/30290814/864113 答案#2:http://stackoverflow.com/a/18733552/864113 – 2016-04-20 08:34:20

回答

2

您在這裏實際上有tail recursion。任何尾遞歸函數都可以用trivially be converted作爲使用循環的迭代函數。

例如:

void foo() { 
    // ... Stuff ... 

    if (someCondition) { 
     foo(); 
    } else { 
     bar(); 
    } 
} 

變爲:

void foo() { 
    while (someCondition) { 
     // ... Stuff ... 
    } 
    bar(); 
} 
+1

在我的問題中有遞歸的解決方案,但我想這樣做eratively! – 2013-02-21 00:27:08

+0

@SophieSperner:是的;並且可以使用上面鏈接中的技術將其轉換... – 2013-02-21 00:28:24

+0

值得指出的是,雖然它具有尾部遞歸的*形式,但Java本身不支持尾遞歸,因此它實際上不是尾遞歸。 – 2013-02-21 01:28:23