dopuzf0898 2016-10-06 05:28
浏览 133
已采纳

拆分数组但每个数组的总和不超过最大值,否则推送到下一个数组索引

I have two arrays, Array 1 being a donor array which has a series of values (not necessarily equal values as in my example). Array 2 is the desired result and would store a series of sub arrays with values from Array 1 where each sub array's total sum would not exceed 25. If it does, the excess would get pushed to the next index in Array 2 where the rules would also apply.

Donor array (Array 1):

$a1=array(10,10,10,10,10,10,10,10,10,10);

Desired output (Array 2):

Array
(
    [0] => 10,10,5
    [1] => 5,10,10
    [2] => 10,10,5
    [3] => 5,10,10
)

Here the code I tried but it gets an error:

Notice: Undefined offset: 10...etc.

$a1=array(10,10,10,10,10,10,10,10,10,10);
$a2=array();
$count=count($a1);

for($i=0;$i<$count;$i++){
    $a2count=array_sum($a2);

    if($a2count>25){
        $i=$i+1;
        $a2[$i]=$a1[$i];
    }
    else{
        $a2[$i]=$a1[$i];
    }
}

print_r($a2);

I don't know what logic to implement and get result I'm looking for.

  • 写回答

4条回答 默认 最新

  • dqpu4988 2016-10-06 06:35
    关注

    Here you go: The logic is not so hard. Hope it helps.

       <?php 
    
       $a1=array(10,10,10,10,10,10,10,10,10,10);
    
       $a2 = [];
       $a3 = [];
    
       $m = 0;
    
       for($i = 0; $i < count($a1); ++$i){      
    
            $m += $a1[$i];
    
            if($m > 25){
    
               $n = $m % 25;
    
               if(array_sum($a2) != 25){
    
                   $a2[] = $n;
    
               }
    
    
               $a3[] = implode(',', $a2);       
    
               $a2 = []; 
    
               $m = $n;
    
               $a2[] = $n;
    
    
             } else{
    
               $a2[] = $a1[$i];
    
             }
    
    
       }
    
       $a3[] = implode(',', $a2);
    
       print_r($a3);
    
       ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题