如何获得数组中每个数字的阶乘值? [英] How to get the factorial value of each number in an array?

查看:86
本文介绍了如何获得数组中每个数字的阶乘值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用此方法获取数组中每个项目的阶乘值,但这仅输出一个值 任何人都可以帮助我找到我做错了什么吗?

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);

推荐答案

您将需要一点递归,因此,您需要通过引用将lambda函数传递给自身:

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);

输出:

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

由于您本质上是在这种情况下(例如)创建数组映射,因此我想对此进行扩展.如果您要在函数mathh()中执行其他计算,则此可能方便,但是如果您要做的只是使用lambda函数创建具有范围的新数组,则可以执行此操作(我们已经创建的相同的lambda):

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);

您将获得相同的输出,因为映射数组的范围(1,5)与原始数组相同:

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
)

这篇关于如何获得数组中每个数字的阶乘值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆