2017-02-23 83 views
1

我必须创建一个函数(使用伪代码),它返回数组中指定元素的深度(包含可选数组),例如:查找数组(或列表等)中指定元素的深度

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

对于“E”它应该返回0,对于“C”,但应返回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; 
}