2017-02-23 84 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; 
}