gpt4 book ai didi

algorithm - 如何将这些产品拆分成包?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:02:37 25 4
gpt4 key购买 nike

我有这组产品:

Product     Quantity    Weight Per Unit
pro#1 7 5kg
pro#2 5 5kg

我想将这些产品拆分成包裹,但包裹的最大重量是 22 公斤。

假设我在数组中有那个表,我想要一个算法来解决这个问题。

到目前为止,这是我尝试过的。

$products = array(
array('weight'=> 5, 'quantity' => 7),
array('weight'=> 5, 'quantity' => 5),
);
$max_weight = 22;
$packs = array();
$packs_count = 1;
foreach ($products as $product){
while ($product['quantity'] != 0) {
$pack[$packs_count]['weight'] = $pack[$packs_count]['weight'] +$product['weight'];
if($pack[$packs_count]['weight'] >$max_weight){
$pack[$packs_count]['weight'] = $pack[$packs_count]['weight'] - $product['weight'];
$packs_count++;
}
$product['quantity']--;
}
}

代码未能正确获取最后一个包。

最佳答案

我在 PHP 中使用这段代码解决了这个问题,任何其他想法都会很棒。无论如何谢谢。

 $products = array(
array('weight'=> 4, 'quantity' => 5),
array('weight'=> 8, 'quantity' => 3),
);
$max_weight = 22;
$packs = array();
$packs_count = 1;

foreach ($products as $product){
while ($product['quantity'] != 0) {
$pack[$packs_count]['weight'] = $pack[$packs_count]['weight'] +$product['weight'];
if($pack[$packs_count]['weight'] > $max_weight){
$pack[$packs_count]['weight'] = $pack[$packs_count]['weight'] - $product['weight'];
$packs_count++;
$pack[$packs_count]['weight'] = $product['weight'];

}
$product['quantity']--;
}
}

print_r($pack);

关于algorithm - 如何将这些产品拆分成包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32023622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com