将小物品装入一个大盒子里

时间:2013-03-02 17:14:27

标签: php algorithm

我找到了一个解决方案来计算购买购物车产品所需的盒子数量。每种产品都有其高度,宽度,长度。大盒子尺寸是固定的

//big box size
$max_height = 20;
$max_width = 30;
$max_length = 40;

foreach ($products as $product) {
    $height = $product->height;
    $width = $product->width;
    $length = $product->length;
}

我知道这是一个3d垃圾箱包装问题,但有没有其他更简单的方法来计算大约箱数?

1 个答案:

答案 0 :(得分:0)

Ingo在原始问题评论中的解决方案很好,这是一个实现。

//big box size
$max_height = 20;
$max_width = 30;
$max_length = 40;
$max_volume = $max_height * $max_width * $max_length;

$tot_height = 0;
$tot_width = 0;
$tot_length = 0;

foreach ($products as $product) {
    $tot_height += $product->height;
    $tot_width += $product->width;
    $tot_length += $product->length;
}

$tot_volume = $tot_height * $tot_width * $tot_length;

$boxes_needed = ceil($tot_volume / $max_volume);

如果你真的要在现实世界中使用它,那么可能会添加一个额外的盒子,因为它不太可能完美地填充盒子音量,除非你是俄罗斯方块的大师:)

相关问题