递归算法学习

题目:写一个函数, 满足如下条件:

$arr = [
    "Name"  => 'test',
    "Data"  => [
            "Uid"   => 1,
            "Name"  => "eva",
            "Thread" => [
                "ID1"   => 22,
                "ID2"   => 33,
                ],
        ],
    "Title" => "get a string",
]; 

数组样例如上,

(1)所有key小写
(2)根据key 升序排列
(3)多维数组 $arr['abc']['efg'] = 1变成 abc.efg = 1
应用场景是什么?

解答:

<?php
$arr = [
    "Name"  => 'test',
   "Data"  => [
            "Uid"   => 1,
            "Name"  => "eva",
            "Thread" => [
                "ID1"   => 22,
                "ID2"   => 33,
                ],
        ],
    "Title" => "get a string",
]; 
$testobj = new test();
$testobj->lower($arr);

$prefix = "";
$newArr = [];
$testobj->getPrefix($arr,$prefix,$newArr);
ksort($newArr);
$finalStr = "";
foreach ($newArr as $key=>$value){
    $finalStr .= $key."=".$value."&";
}
var_dump(rtrim($finalStr,"&"));
class test{
   
    function getPrefix($arr,&$prefix,&$newArr){
        foreach ($arr as $key=>$value){
            if(is_array($value)){
                $prefix .=$key.".";
                self::getPrefix($value,$prefix,$newArr);
                $prefix = "";
            }else{
                $newArr[$prefix.$key]=$value;
            }
            
        }
        
    }
   
    function lower(&$arr){
        $arr = array_change_key_case($arr);
        foreach ($arr as $key=>&$value){
            if(is_array($value)){
                self::lower($value);
            }
            
        }
    }
}
?>

 题目:用户充值优惠计算方法:

解答:

<?php
    var_dump(discountAmount(800));
    //$amount 为原价
    function discountAmount($amount){
    //价格 => 折扣
$arr = [ 10 =>1000,   100=> 999, 200=>998, 300=>997, 400=>996, 500=>995, 600=>994, 700=> 993, 800=> 992, 900=>991, 1000=> 990, 10000=> 989, 50000=>988, 500000=> 987, ]; krsort($arr); foreach ($arr as $min=>$discount){ if($amount>=$min){ return $dicountAmount = $amount * $discount /1000; } } } ?>

 

题目:

1~50 80
51~100 70
101~500 50
501~1000 30
1001~6000 10
6001及以上 1
假如某个用户下单60个, 则该用户需付费总数是: 50*80 + 10*70. 请写一个递归函数。
下单110个: 50*80 +50*70 + 10 *50= 4000 + 3500 + 500 = 8000

function getTotalAmount($num){
    $total = 0;
    $arr = [
       6000 => 1,
       1000 => 10,
       500  => 30,
       100  => 50,
       50   => 70,
       0    => 80,
       ];
       
       foreach ($arr as $key=>$value){
           if($num>$key){
               $tmp = $num-$key;
               $total +=getTotalAmount($key);
               return $total +=$tmp*$value;
           }
       }
}
var_dump(getTotalAmount(110));

 

posted @ 2019-03-19 15:28  饶翠  阅读(165)  评论(0编辑  收藏  举报