dongsu4345 2014-11-28 02:02
浏览 64

PHP包装解决方案 - 如何平均分配项目

Refer to article How to divide items equally in stackoverflow, the solution was suggested in Ruby script. But I had translated into PHP script that maybe could help someone to have better idea, here is the code:

Let say the list of bags that we have

$list_of_bags = array(11, 41, 31, 15, 15, 66, 67, 34, 20, 42, 22, 25); rsort($list_of_bags);

Total weight of all bags

$weight_of_bags = array_sum($list_of_bags);

How many containers do we have at our disposal?

$number_of_containers = 4;

How much should one container weight?

$weight_per_container = $weight_of_bags / $number_of_containers;

We make an array containing an empty array for each container

$containers[] = array();
$total = 0;

For each bag

foreach ($list_of_bags as $bag) { for($i=0; $i

    $total = (isset($containers[$i])) ? array_sum($containers[$i]) : 0;
    if($total + $bag < $weight_per_container){
        $containers[$i][] = $bag;
        break;
    }
} }  

output all containers with the number of items and total weight

foreach ($containers as $index=>$container) {
echo "container $index has ";
echo count($container);
echo " ";
echo "items and weigths: ";
echo array_sum($container);
echo " "; }

The output should be as follow:

container 0 has 3 items and weigths: 83
container 1 has 3 items and weigths: 96
container 2 has 2 items and weigths: 87
container 3 has 2 items and weigths: 76
container 4 has 2 items and weigths: 47

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)