2017-02-23 4 views
1

배열의 지정된 요소의 깊이를 반환하는 함수 (의사 코드 사용)를 작성했습니다 (예 : 내부의 선택적 배열 포함). "E"를배열 배열 (또는리스트 목록 등)에서 지정된 요소의 깊이 찾기

def array[] = {"a", {"b", {"c"}, "d"}, {{{}}}, "e"}; 

어레이 내에 지정된 요소가없는 경우는해야 "C"에 대한 0을 반환하면, 그것을 반환해야 등 2 , 함수는 -1을 리턴해야한다. ,

나는 몇 번 시도했지만, 나는 우아한 (및 작업 ..) 솔루션에 대한 아무 생각도 없어에만이 :

func foo(array[], var element) { 
    int depth = 0; 
    boolean found = false; 
    boolean recursion = false; 
    boolean foundInRecursion = false; 

    for (int i = 0; i < array.length; i++) { 
     if (array[i] instanceof array[]) { 
      depth++; 
      recursion = true; 
      foo(array[i], element); 
      recursion = false; 
     } else if (array[i] == element) { 
      if (recursion) { 
       foundInRecursion = true; 
      } else { 
       found = true; 
      } 
     } 
    } 

    if (foundInRecursion) { 
     return depth; 
    } else if (found){ 
     return 0; 
    } else { 
     return -1; 
    } 
} 

난 정말 어떤 도움을 주셔서 감사합니다 것입니다! 주셔서 감사합니다 의사에

답변

0

는 :

func depth(array[], var element) { 
    /* this function returns how deep the element is in the given array */ 
    for (int i = 0; i < array.length; i++) { 
     current = array[i] 

     if current == element { 
      return 0; // element is right in the array we are given 
     } 

     if (current instanceof array[]) { 
      // Whoa, subarray! How deep our element is in it? 
      subdepth = depth(current, element) 
      if subdepth >= 0 { 
       // Element was found in *sub*-array, so add 1 to the depth 
       return subdepth + 1; 
      } 
     } 
    } 
    // If we are here, we found nothing 
    return -1; 
} 
+0

코드는 그대로 작동합니다. 모든 것을 꼬리 재귀 적으로 만들기 위해 현재의 깊이를 전달하는 것이 가능합니다. 더 명확한 방법으로 아이디어를 보여줄 수는 없습니다. 명확한 설명을 주신 덕분에 – avysk

+0

- 오늘 뭔가를 배웠습니다. :) –

0

나는 그런 우아한 해결책은 각 레이어를 넘어 반복적 인 코드해야한다고 생각합니다.

public int IterativeDepth(List<Object> lst, T element) 
{ 
    // Set the first iteration 
    int depth = 0; 
    List<Object> next = new List<Object>(); 

    while (! IsNullOrEmpty(lst)) 
    // For each layer 
    { 
     foreach (var current in lst) 
     // For each element of a layer 
     { 
      if (current instanceof T && current == element) 
      // Found it, return the depth 
      { 
       return depth; 
      } 

      if (current instanceof List) { 
      // It's a list, append it to the next iteration 
       next.Add(current); 
      } 
     } 

     // Set the next iteration 
     lst = next; 
     next.clear(); 
     depth += 1; 
    } 

    // Found nothing 
    return -1; 
}