簡體   English   中英

遞歸結果堆棧

[英]Recursion Result stack

傳遞此遞歸函數結果的最干凈方法是什么?

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;

}
?>

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

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)

您的思維方式可能是保持$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;


}

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

當您執行像這樣的遞歸函數時,如果它們是尾遞歸的,則對性能有好處(實際上,我不確定php是否有這種優化方法,我希望如此)。 在這里,您有$ count可以用作累加器,但不要使用它。

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

這樣,它的工作原理是尾遞歸:-)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM