2010-02-22 8 views
1

유사 변경 모든 인덱스와 N 중첩 루프 : Is there any way to do n-level nested loops in Java?재귀 함수 - 이에

는 I는 모든 인덱스 루프의 깊이에 의존 N 중첩 루프를 생성하는 재귀 함수, 을 만들. 그러니까 기본적으로, 나는 반복적으로이 작업을 수행 할 수 :

// 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-loop를 감싸는 클래스를 보게 될 것이라고 생각합니다.) "어려운"부분은 가변적 인 배열이나 큐를 사용하여 수행 할 수있는 인덱스를 추적하고 있으며, 하지만 불변의 콜렉션에 아이템을 보관할 때 훨씬 쉽게 되돌릴 수 있습니다. – Juliet

답변

2

그것의 C#을하지만, 자바 쉽게 convertable해야한다 :

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

이 작품! 감사. 그러나 generics가 Java의 정적 컨텐츠에서 작동하도록 할 수는 없습니다. 그러나 그것은 자바 일 수 있습니다, 나는 그것을 많이 디버깅 귀찮게하지 않았다. –