2017-02-23 18 views
1

配列内の指定された要素の深さを返す関数を作成する必要があります(例: 「C」は、「E」、それべき戻り0、それがなければならない戻り2等 配列、機能すべきリターン-1には指定された要素がありません場合について配列の配列(またはリストのリストなど)内の指定された要素の深さの検索

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

。 、

は、私は何度か試してみたが、私は、エレガントな(と作業...)ソリューションをさっぱりだがこれだけ:

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; 
} 
関連する問題