如何在4盒平分项目? [英] How to divide items equally in 4 boxes?

查看:136
本文介绍了如何在4盒平分项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有7 以不同的权重。其实PHP数组包含此数据。

Suppose i have 7 bags with different weight. Actually a php array contains this data.

Bag A    60 Kg
Bag B    80 Kg
Bag C    20 Kg
Bag D    10 Kg
Bag E    80 Kg
Bag F    100 Kg
Bag G    90 Kg

在PHP它看起来像这样

In php it will look like this

    Array
(
    [30] => 60
    [31] => 120
    [32] => 120
    [33] => 60
    [35] => 180
)

现在我必须在划分的 4容器中的所有 7袋 同样通过平衡重量存在。
但我不能打破的袋子来管理体重。如何做到这一点请建议我。如何建立一个公式或 PHP 功能,将分发所有行李平衡重量存在。
有一个在容器的容量没有限制。而它也没有必要让所有容器的重量分配后相等。我只是需要一个负载均衡。
先谢谢了。

Now i have to divide all 7 bags in 4 container equally by balancing there weight. But i cannot break the bag to manage weight. How to do this please suggest me. How can i build a formula or php function which will distribute all bags balancing there weight. There is no limitation in container capacity. And its also not necessary to have all containers weight equal after distribution. I just need a load balancing. Thanks in advance.

推荐答案

创建得到了产品重量,并返回一个包数的函数 - 其中有至少可用空间还是足够的,以适应之一。把它收入囊中。重复,直到完成。

Create a function that gets a product weight and returns a bag number - the one which has the least free space that's still enough to fit. Put it in the bag. Repeat until done.

$bags = array(60,80,20,10,80,100,90);
$containers = array(1=>100,2=>100,3=>100,4=>100); // number -> free space
$placement = array();

rsort($bags); // biggest first - usually it's better

function bestContainerFor($weight) {
    global $containers;
    $rest = 0;
    $out = 0; // in it won't change $weight fits nowhere
    foreach($containers as $nr=>$space) {
        if($space<$weight) continue; // not enough space
        if($space-$weight<$rest) continue; // we have a better case
        $rest = $space-$weight;
        $out = $nr;
    }
    if($out) $containers[$out]-=$weight; // occupy the space
    return $out;
}

foreach($bags as $nr=>$w) {
    $p = bestContainerFor($w);
    $placement[$nr] = $p; // for later use; in this example it's not needed
    if( $p) print "Bag $nr fits in $p<br>";
    if(!$p) print "Bag $nr fits nowhere<br>";
}

这不是测试。如果你给我你的code的一些细节,我会努力去适应。这正说明了它的原则。

It's not tested. If you give me some details of your code I'll try to adapt. This just shows the principle of it.

注意


  • 它与可变的容器尺寸,

  • 它给你的每件行李的位置,而不是总重量,

  • 这是不是最佳的平等分配,只是给出了一个很好的例子

这篇关于如何在4盒平分项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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