简体   繁体   中英

Recursion PHP - after one permutation why doesn't this recursive function return a value?

function noOfPermutations($n, $permutation){
    $array = str_split($n);
    if(count($array)==1) {
        echo $permutation."\n";
        return $permutation;
    }else{
        $permutation++;
        noOfPermutations(array_sum($array), $permutation);
    }
}

echo "--".noOfPermutations(91,0)."--\n";

I'm trying to find the number of permutations for the sum of the digits in $n becomes single. eg 91 -> 9+1 = 10 -> 1+0 = 1. This took 2 rounds so would return 2. The function works fine if $n starts as a single digit number (it correctly returns 0) however more than one permutation and it just returns null. The first echo in the function outputs the correct value but the echo outside the function returns null.

The solution is in your title after one permutation why doesn't this recursive function return a value? :

return noOfPermutations(array_sum($array), $permutation);

You might also look at array_reduce .

Because you're doing nothing with the result. You go one deeper in the else, but do nothing with the outcome of that. I'm guessing it should be something along the lines of:

function noOfPermutations(int $n, int $permutation = 0){
    $array = str_split($n);
    if( count($array) > 1 ) {
        $permutation += noOfPermutations(array_sum($array),  $permutation);
        //  ^^--- Now we actually do something with the result 
    }

    return $permutation; 
}

I've added a little codeformat and typehint as well


Alternatively, you can make the $permutation by reference, that way you dont have to return it. I dont recommend it, but it might be a solution for someone sometime.

you are not doing anything with the returned value, I slightly re-elaborated your function in this way

function noOfPermutations($n, $permutation) {
    $array = str_split($n);
    if(count($array)==1) {
        echo "==>" . $permutation."\n";
    }else{
        $permutation++;
        $permutation = noOfPermutations(array_sum($array), $permutation);
    }
    return $permutation;
}

echo "--".noOfPermutations(91,0)."--\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM