2010-02-22 42 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