php - 帮帮看看这个简单的算法

查看:85
本文介绍了php - 帮帮看看这个简单的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

写的不好,求大家优化
一个用户ID的数组

$uids = [1,2,3,5,6,8,9,11,13,25,65];

这个数组的每一个键值代表一个UID
金额数组

$amounts = [
    1=>12000,
    2=>500,
    3=>11000,
    5=>1000,
    6=>11000,
    8=>12000,
    9=>12000,
    11=>11000,
    13=>12000,
    25=>22000,
    65=>123123
];

此数组的键名和$uid数组的键值对应。
循环$uids这个数组,取出对应的金额$amount,
如果这个金额大于等于12000($boundary),就在总金额($totals)加上这个$amount
如果这个金额小于12000,就再向下循环,循环到这几个$amount相加大于等于12000,然后在总金额($totals)加上这几个$amount的和
最多取三层。
最后得出$totals的值。
我现在的代码:

<?php
$boundary = 12000;
$uids= [1,2,3,5,6,8,9,11,13,25,65];
$amounts = [
    1=>12000,
    2=>500,
    3=>11000,
    5=>1000,
    6=>11000,
    8=>12000,
    9=>12000,
    11=>11000,
    13=>12000,
    25=>22000,
    65=>123123
];
$totals = 0;
foreach($uids as $k => $uid){
    $amont = $amounts[$uid];
    if($amont >= $boundary){
        $totals += $amont;
    }else{
        $next = get_next($uids ,$k+1 ,$amont);
        if($next && is_array($next)){
            $curKey = $next[0]; //amouts index 3
            $totals+=$next[2];
            //再向下获取一层
            $nextKey = $curKey+1;
            if(!isset($uids[$nextKey])){
                break;
            }
            $nextUid = $uids[$nextKey];
            $nextAmount = $amounts[$nextUid];
            if($nextAmount >= $boundary){
                $totals+=$nextAmount;
            }else{
                $last = get_next($uids ,$nextKey+1 ,$nextAmount);
                if($last && is_array($last)){
                    $totals+=$last[2];
                }
            }
        }
        break; //跳出主循环
    }
}
echo $totals;
exit;

function get_next($uids ,$start ,$prevAmount){
    global $amounts ,$boundary;
    $leaves = array_slice($uids ,$start ,count($uids),true);
    if($leaves){
        foreach($leaves as $k=>$uid){
            $amount = $prevAmount+$amounts[$uid];
            if($amount >= $boundary){
                return [$k ,$uid ,$amount];
                break;
            }else{
                return get_next($uids ,$k+1 ,$amount);
            }
        }
    }
    return 0;
}

得出$totals=47500

解决方案

好像不用那么复杂吧,我不知道有没有正确理解楼主的意图,我以下代码可以输出47500

$boundary = 12000;
$max_depth = 3;
$total = 0;
foreach($uids as $uid) {
    if($max_depth>0) {
        if($amounts[$uid] >= $boundary) {
            --$max_depth;
        }
        $max_depth && $total += $amounts[$uid];
    }
}
echo $total;

这篇关于php - 帮帮看看这个简单的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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