douxing6532 2013-05-14 20:19
浏览 69
已采纳

Php Division剩余和阵列

I have an array $blocks It has 4 items with constant values A, B, C, D

$blocks["a"] = 20;
$blocks["b"] = 1000;
$blocks["c"] = 10000;
$blocks["d"] = 50000;

Another function returns a value, lets say 358020 (It's usually high but can drop to a few tens

How would I write a function that will take this value and return an array of how many of each item exists.

Example output something like:

 $output["a"] = 1;
 $output["b"] = 3;
 $output["c"] = 0;
 $output["d"] = 7;

Starting with the largest block, how many of that block fits into the value, then the remainder is passed to the next largest, and so on...

  • 写回答

1条回答 默认 最新

  • duande1146 2013-05-14 21:00
    关注
    calculateNumberCredits(25000);
    
    function calculateNumberCredits($experience) {
    
        # The credits we have
        $credits = array(
            'a' => '10000',
            'b' => '2000',
            'c' => '1000',
        );
    
        # Keep track of the amount needed per credit
        $timesCreditNeeded = array();
    
        # Start calculating the amount per credit we need
        foreach($credits as $creditID => $creditAmount) {
    
            # 1) Calculate the number of times the amount fits within the amount of experience
            $times = floor($experience / $creditAmount);
    
            # 2) Calculate the remainder of the above division en cache is for the next     calculation
            $experience = $experience % $creditAmount;
    
            # 3) Cache the number of times the credit fits within the experience
            $timesCreditNeeded[$creditID] = $times;
    
        }
    
        echo '<pre>';
        print_r($timesCreditNeeded);
    
        return $timesCreditNeeded;
    
    }
    
    // Will return Array ( [a] => 2 [b] => 2 [c] => 1 )
    

    I loop through the credits you have in your system. In this example the credits are order from high to low. When this is not the case you should order them te get the desired result.

    1) For each credit i try to find the max number of times the credit fits within the experience of the particular user. Because floatnumber make no sense we floor() the result of the division.

    2) After i found the number of times the credit fits, I calculate the remainder for the next iteration (next credit). You can find the remainder by calculating the modulus.

    3) Last but not least I cache the number of times the credit fits.

    Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳