php 贪婪算法

说 有一些大小不一的东西,要装到 固定的盒子里面,最少需要几个盒子。

   public function test()
    {
       $res = (new Tool())->addOrderActionNote([]);;exit;
        exit;
//物品
        $items[0] = 60;
        $items[1] = 45;
        $items[2] = 35;
        $items[3] = 20;
        $items[4] = 20;
        $items[5] = 20;
        $box_volume_count = 100; //每个盒 子的最大容积
        $box_count = 0; //共用盒子总数
        $item_count = count($items);
        $box = array();//盒 子数组
        for ($itemindex = 0; $itemindex < $item_count; $itemindex++) {
            $_box_index = false;
            $_box_count = count($box);
            for ($box_index = 0; $box_index < $_box_count; $box_index++) {
                if ($box[$box_index]['volume'] + $items[$itemindex] <= $box_volume_count) {
                    $_box_index = $box_index;
                    break;
                }
            }
            if ($_box_index === false) {
                $box[$_box_count]['volume'] = $items[$itemindex];
                $box[$_box_count]['items'][] = $itemindex;
                $box_count++;
            } else {

                $box[$_box_index]['volume'] += $items[$itemindex];
                $box[$_box_index]['items'][] = $itemindex;
            }
        }
        dump($box);
    }

得到:

array(3) {
  [0] => array(2) {
    ["volume"] => int(95)
    ["items"] => array(2) {
      [0] => int(0)
      [1] => int(2)
    }
  }
  [1] => array(2) {
    ["volume"] => int(85)
    ["items"] => array(3) {
      [0] => int(1)
      [1] => int(3)
      [2] => int(4)
    }
  }
  [2] => array(2) {
    ["volume"] => int(20)
    ["items"] => array(1) {
      [0] => int(5)
    }
  }
}

猜你喜欢

转载自blog.csdn.net/qq_22823581/article/details/81459539