2011-01-30 115 views
0

將這個遞歸函數的結果返回的最簡潔的方法是什麼?遞歸結果堆棧

function recursion_trigger($input, $count = 0){ 

     if(!empty($input)){ 
       array_pop($input); 
       $count++; 
       if(!empty($input)){ 
       recursion_trigger($input,$count); 
       } 
     } 

echo $count; 
return $count; 


} 

目前它正在返回最上面的電話當然是一個。

///////作爲一個額外的問題,這是完整的功能,你可以在這裏使用尾遞歸嗎?輸出是一個數組,我正在構建,因爲我通過值。

<?php  
//Page best viewed from page source 

//Takes an array of objects that have ID and Parent and organizes the tree into an array representing a set of objectID's by depth 

// poor spelling ahead =P 

function level_keys($array,$depth=-1,$level=0,$output=null){ 

// initialize the functions parameters run once at start and not in subsequent self calls 

if($level == 0 && $depth != 0){ 
    $output[][]=0; 
    $level++; 
     foreach($array as $key=>$node){ 
      if($node->parent==0){ 
       $output[$level][] = $node->id; 
       unset($array[$key]); 
      } 
     } 
      unset($key); unset($node); 
$level++; 
$depth--; 

} 

// set recursion loop and run main part of function 

if ( !empty($array) && $depth != 0){ 

    echo 'depth:'.$depth."\n"; 

    foreach($output[$level-1] as $parent){ 
     foreach($array as $key=> $child){ 
      if($parent == $child->parent){ 
      $output[$level][] = $child->id; 
      unset($array[$key]); 
      } 
     } 
    } 
     unset($id); unset($parent); unset($key); unset($child); 
$depth--; 
$level++; 
     if(!empty($array) && $depth !=0){ 
      // make sure to pass the output back out to the top most level 
      $output = level_keys($array,$depth,$level,$output,$depth_at); 
     } 
} 

return $output; 

} 
?> 

回答

1

我想你真正需要的不是計算數組中元素的數量。

當你做這樣的遞歸函數時,如果它們是尾遞歸的(實際上,我不確定PHP是否有這種優化,我希望如此),它對性能是有好處的。這裏有$ count可以用作累加器,但不要使用它。

function recursion_trigger ($input, $count = 0) 
{ 
    if (!empty($input)) { 
    array_pop($input); 
    return recursion_trigger($input, $count + 1); 
    } 
    return $count; 
} 

這種方式工作,是尾遞歸:-)。

1

您應該返回值更新$count變量recursion_trigger

if(!empty($input)){ 
    $count = recursion_trigger($input,$count); 
} 

編輯:

希望以下將幫助你想象它是如何工作的:

recursion_trigger (array("This", "Is", "A", "Sample"), 0) 
    recursion_trigger (array("This", "Is", "A"), 1) 
    recursion_trigger (array("This", "Is"), 2) 
     recursion_trigger (array("This"), 3) 
     recursion_trigger (array(), 4) 
+0

謝謝你完全是這樣。我明白它爲什麼可行,但我仍然無法想象它是如何工作的。 – Prospero 2011-01-30 15:36:47

+0

@Doodle:查看更新後的帖子。 – 2011-01-30 15:41:50

1

你在想的方式可能是沿着林es $count是持久性的,而不是因爲按價值調用。這個版本,使用引用,也適用。

function recursion_trigger($input, &$count = 0){ 

     if(!empty($input)){ 
       array_pop($input); 
       $count++; 
       if(!empty($input)){ 
       recursion_trigger($input,$count); 
       } 
     } 

echo $count; 
return $count; 


} 
+0

我曾經考慮過,但這最終將成爲Java中的一個函數。我只是試圖想象一切如何運作,PHP是一種非常快速的語言。謝謝。 – Prospero 2011-01-30 20:51:57