我需要一种类似于for循环重新评估测试条件的行为的算法

问题描述 投票:0回答:1

我正在迭代放置在容器中的一系列盒子。例如,容器可以存储级别“10”的盒子。如果一个数组是[6,5,2]。我将有两个容器:一个带[6,2],一个带[5],数组迭代它抓住6,跳过5并抓住2.它跳过5因为6 + 5是11.容器不能有更多跳过的5放在一个单独的数组中,以便稍后迭代。

下面我总结一下我的问题。这不是一个有效的代码。我只是在证明我的问题。

$boxes = [2, 3, 2, 5, 8, 2, 10, 2, 5, 6]; // my boxes

$separated_boxes = [];
$items = [];

for($i = 0; $i < count($boxes); $i++){

 $items[] = $box[$i]; //add box to array

  $result = Class::packBoxes($items) // check if the box(es) can be packed

 //if the current box cannot be packed it is separated
  if($result == false)
  {
     $separated_boxes[] = $box[$i];
  }

   //if the loop reaches the end a new loop should start with the separated boxes

//Apparently I cannot do this because the for conditions are avalidated only once

    if((($i + 1) == count($boxes) && count($separated_boxes) > 0)){

               $itens = [];
                $i = 0;
                $boxes= $separated_boxes;
                $separated_boxes= [];
       }
 }

   packBoxes($boxes)
{
  if(canPack($box)
   {
      return true;
   }
   else{
       return false;
   }
}

我怎么解决这个问题?

php algorithm logic
1个回答
0
投票

你正在考虑这种错误的循环。 for-like循环通常用于为输入中的每个项目执行一次操作。

但这不是你需要的东西。您需要重复检查输入中的项目,将它们放在一边并为它们返回,直到所有项目都分配到容器中。

有很多方法可以编写它(循环,迭代器,递归函数,带逻辑的对象......)。在循环方面你可以尝试像这样的do-while

do {

  // take items out of $boxes until you fill <=10 units container

} while( ! empty( $boxes ) );
© www.soinside.com 2019 - 2024. All rights reserved.