代码之家  ›  专栏  ›  技术社区  ›  Dycey

货架堆码伪码

  •  2
  • Dycey  · 技术社区  · 15 年前

    假设我有一些序列号的项,宽1-n个单位,需要以行显示。每行宽m单位。我需要一些伪代码来为我输出行,以便保持m的宽度限制。这不是背包的问题,因为物品必须保持序列号顺序-行末的空白处可以。

    我一直在追寻这一点,部分原因是我在PHP和jquery/javascript中都需要它,因此对伪代码的请求……

    4 回复  |  直到 15 年前
        1
  •  3
  •   bdonlan    15 年前
    while (!items.isEmpty()) {
      rowRemain = m;
      rowContents = [];
      while (!items.isEmpty() && rowRemain > items[0].width) {
        i = items.shift();
        rowRemain -= i.width
        rowContents.push(i);
      }
      rows.push(rowContents);
    }
    

    运行时间为(项目数)

        2
  •  0
  •   Bryan    15 年前

    模数是你的朋友。我会做如下的事情:

    $items = array(/* Your list of stuff */);
    $count = 0;
    $maxUnitsPerRow = 4; // Your "m" above
    
    while ($item = $items[$count]) {
     if ($count % $maxUnitsPerRow == 0) {
        $row = new row();
     }
    $row->addItemToRow($item);
    $count++;
    }
    
        3
  •  0
  •   OIS    15 年前

    下面是一个可选的PHP代码…

    function arrayMaxWidthString($items, $maxWidth) {
        $out = array();
        if (empty($items)) {
            return $out;
        }
    
        $row = $maxWidth;
        $i = 0;
    
        $item = array_shift($items);
        $row -= strlen($item);
        $out[0] = $item;
    
        foreach ($items as $item) {
            $l = strlen($item);
            $tmp = ($l + 1);
            if ($row >= $tmp) {
                $row -= $tmp;
                $out[$i] = (($row !== $maxWidth) ? $out[$i] . ' ' : '') . $item;
            } elseif ($row === $maxWidth) {
                $out[$i] = $item;
                ++$i;
            } else {
                ++$i;
                $row = $maxWidth - $l;
                $out[$i] = $item;
            }
        }
        return $out;
    }
    
        4
  •  0
  •   Dycey    15 年前

    对于它的价值,我想我已经找到了我想要的东西,对于PHP——但不确定是否有一个更简单的方法……

    <?php
    // working with just a simple array of widths...
    $items     = array(1,1,1,2,1,1,2,1);
    $row_width = 0;
    $max_width = 2;
    
    echo "Begin\n"; // begin first row
    foreach($items as $item=>$item_width) {
      // can we add item_width to row without going over?
      $row_width += $item_width;
      if($row_width < $max_width) {
        echo "$item_width ";
      } else if($row_width == $max_width) {
        echo "$item_width";
        echo "\nEnd\nBegin\n"; // end last row, begin new row
        $row_width = 0;
      } else if($row_width == 2* $max_width) {
        echo "\nEnd\nBegin\n"; // end last row, begin new row
        echo "$item_width";
        echo "\nEnd\n"; // end new row
        $row_width = 0;
        if($item < count($items)) echo "Begin\n"; // new row
      } else if($row_width > $max_width) {
        echo "\nEnd\nBegin\n"; // end last row, begin new row
        echo "$item_width";
        $row_width = $item_width;
      }
    }
    echo "\nEnd\n"; // end last row
    
    ?>