2010-02-22 72 views
1

與此類似:Is there any way to do n-level nested loops in Java?遞歸函數 - N的嵌套循環不斷變化indicies

我想創建一個遞歸函數,其生成N個嵌套循環,其中indicies取決於環路的深度。所以基本上,我想遞歸地做到這一點:

// N = 3, so we want three nested loops 

for(int i1 = 0; i1 < max; i1++){ 
    for(int i2 = i1+1; i2 < max; i2++){ 
     for(int i3 = i2+1; i3 < max; i3++){ 
      int value1 = getValue(i1); 
      int value2 = getValue(i2); 
      int value3 = getValue(i3); 
      doSomethingWithTheValues(...); 
     } 
    } 
} 

我看過的其他問題的答案,並試圖修改答案(由oel.neely),但沒有運氣。我的猜測是,它只需要一個小小的修改,但現在,我只是混淆了我自己!

+0

我個人建議不要修改joel.neely的答案。雖然它給出了正確的答案,但我認爲你的團隊中的每個人都會看到一個包裝for循環的類;)「硬」部分跟蹤索引,你可以使用可變數組或隊列來完成索引,但是當你在一個不可變的集合上持有物品時,它更容易回溯。 – Juliet 2010-02-22 05:24:43

回答

2

它的C#,但應該是容易轉換到Java:

class ImmutableStack<T> 
{ 
    public readonly T Head; 
    public readonly ImmutableStack<T> Tail; 

    public ImmutableStack(T head, ImmutableStack<T> tail) 
    { 
     this.Head = head; 
     this.Tail = tail; 
    } 

    public static ImmutableStack<T> Cons(T head, ImmutableStack<T> tail) 
    { 
     return new ImmutableStack<T>(head, tail); 
    } 

    public static ImmutableStack<T> Reverse(ImmutableStack<T> s) 
    { 
     ImmutableStack<T> res = null; 
     while (s != null) 
     { 
      res = Cons(s.Head, res); 
      s = s.Tail; 
     } 
     return res; 
    } 
} 

class Program 
{ 
    static void AwesomeRecursion(int toDepth, int start, int max, ImmutableStack<int> indices) 
    { 
     if (toDepth < 0) 
     { 
      throw new ArgumentException("toDepth should be >= 0"); 
     } 
     else if (toDepth == 0) 
     { 
      Console.Write("indices: "); 
      indices = ImmutableStack<int>.Reverse(indices); 
      while (indices != null) 
      { 
       Console.Write("{0}, ", indices.Head); 
       indices = indices.Tail; 
      } 
      Console.WriteLine(); 
     } 
     else 
     { 
      for (int i = start; i < max; i++) 
      { 
       AwesomeRecursion(toDepth - 1, i + 1, max, ImmutableStack<int>.Cons(i, indices)); 
      } 
     } 
    } 


    static void Main(string[] args) 
    { 
     AwesomeRecursion(4, 1, 10, null); 
     Console.WriteLine("Done"); 
     Console.ReadKey(true); 
    } 
} 

我們保持一個不變的堆棧上的指標,因爲它使回溯所以比可變棧或隊列容易得多。

+0

這個工程!謝謝。然而,我不能讓泛型在java中的靜態內容中工作。但它可能是一個Java的東西,我沒有打擾太多的調試。 – 2010-02-22 13:26:28