How to get the factorial value of each number in a

2019-02-25 18:36发布

问题:

I am trying to get an factorial value of each item in array by using this method but this outputs only one value can any body help me finding where i am doing wrong?

   function mathh($arr, $fn){


            for($i = 1; $i < sizeof($arr); $i++){
            $arr2 = [];
          $arr2[$i] = $fn($arr[$i]);

        }
        return $arr2;
    }

    $userDefined = function($value){
       $x = 1;
         return $x = $value * $x;


    };

        $arr = [1,2,3,4,5];
        $newArray = mathh($arr, $userDefined);

        print_r($newArray);

回答1:

You're going to need a little recursion so in order to do that you need to pass the lambda function into itself by reference:

function mathh($arr, $fn){
    $arr2 = []; // moved the array formation out of the for loop so it doesn't get overwritten
    for($i = 0; $i < sizeof($arr); $i++){ // starting $i at 0
        $arr2[$i] = $fn($arr[$i]);
    }
    return $arr2;
}

$userDefined = function($value) use (&$userDefined){ // note the reference to the lambda function $userDefined
   if(1 == $value) {
       return 1;
   } else {
       return $value * $userDefined($value - 1); // here is the recursion which performs the factorial math
   }
};

$arr = [1,2,3,4,5];
$newArray = mathh($arr, $userDefined);
print_r($newArray);

The output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 6
    [3] => 24
    [4] => 120
)

I wanted to expand on this some since you're essentially (in this case) creating an array map. This could be handy if you're doing additional calculations in your function mathh() but if all you want to do is use the lambda function to create a new array with a range you could do this (utilizing the same lambda we've already created):

$mapped_to_lambda = array_map($userDefined, range(1, 5));
print_r($mapped_to_lambda);

You will get the same output, because the range (1,5) of the mapped array is the same as your original array:

Array
(
    [0] => 1
    [1] => 2
    [2] => 6
    [3] => 24
    [4] => 120
)