我有這個組的產品:如何將這些產品拆分成包?
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']--;
}
}
該代碼未能獲得最後一個包的權利。
[分享你的研究可以幫助每個人](http://meta.programmers.stackexchange.com/questions/6559/why-is-research-important)。告訴我們你試過了什麼,以及它爲什麼不符合你的需求。這表明你已經花時間去嘗試幫助你自己了,它使我們避免重申明顯的答案,最重要的是它可以幫助你得到更具體和相關的答案。另見[問] – gnat
@gnat我更新了這個問題。謝謝。 –
你爲什麼不在堆棧溢出問? http://meta.stackexchange.com/a/129632/165773 – gnat