1
  • If the cost of all the items in an order is more than $250, split those items into multiple packages, otherwise one package would be enough.
  • If the items in the same order are split into multiple packages, then the weight of the packages should be equally distributed over the packages to save courier charges.
  • While splitting, NO PACKAGE can have a total price equal or above $250

    Name Price($) Weight(g)

  • List item

I worked a lot on following logic but didn't achieve. Please help me to solve this Thanks in advance

I have tried with the following code, able to decide the code based on weight but when comes to price logic it fails.

$in = array(10=>200, 30=>300, 200=>10, 20=>500, 40=>10, 100=>20);
function devideArray($in){

// Sort array decreasing
arsort($in, SORT_NUMERIC);

// Start with two empty arrays
$arr1 = $arr2 = array();

// Put the next value in the array in the array with the lowest sum
foreach ($in as  $k=>$value){
   // echo $k."===".$value; echo "<br>";
  if (array_sum($arr2) > array_sum($arr1)) $arr1[$k] = $value; else $arr2[$k] = $value;

}
// Wrap in array (as in question)
$out = array($arr1,$arr2);
return $out;
}
$array = devideArray($in);
echo "<pre>";print_r($array);echo "</pre>";

Package 1

Items - Item 1, Item 3, item 7 Total weight - 510g Total price - $240

Package 2

Items - Item 4, Item 6, item 2 Total weight - 530g Total price - $160 Courier price - $15

Srinivas
  • 21
  • 3
  • 1
    please add the data as text to the question, better as an array of objects. btw, why javascript? – Nina Scholz Apr 28 '19 at 12:30
  • 1
    https://stackoverflow.com/questions/6597180/how-to-divide-a-set-into-two-subsets-such-that-difference-between-the-sum-of-num – Nick Apr 28 '19 at 12:30
  • 1
    Possible duplicate of [How to divide a set into two subsets such that difference between the sum of numbers in two sets is minimal?](https://stackoverflow.com/questions/6597180/how-to-divide-a-set-into-two-subsets-such-that-difference-between-the-sum-of-num) – harmonica141 Apr 28 '19 at 12:32

0 Answers0