行に表示する必要がある、幅が 1-n 単位のシリアル番号の付いた項目があるとします。各行は m 単位の幅です。m幅の制限が維持されるように、行を出力する擬似コードが必要です。これはナップザックの問題ではありません。アイテムはシリアル番号順に並べる必要があるためです。行の末尾の空白は問題ありません。
PHP と jQuery/javascript の両方でそれが必要なため、疑似コードの要求があったため、私はこれについて尻尾を追いかけてきました....
行に表示する必要がある、幅が 1-n 単位のシリアル番号の付いた項目があるとします。各行は m 単位の幅です。m幅の制限が維持されるように、行を出力する擬似コードが必要です。これはナップザックの問題ではありません。アイテムはシリアル番号順に並べる必要があるためです。行の末尾の空白は問題ありません。
PHP と jQuery/javascript の両方でそれが必要なため、疑似コードの要求があったため、私はこれについて尻尾を追いかけてきました....
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);
}
実行時間は Θ(アイテム数)
価値があるので、私は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
?>
これが代替の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;
}
モジュラスはあなたの友達です。私は次のようなことをします:
$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++;
}