Я думаю, что самый простой способ взглянуть на это - с помощью итерации между пределами
* 1003 Е.Г. *
/**
* balancedWordWrap
*
* @param string $input
* @param int $maxWidth the max chars per line
*/
function balancedWordWrap($input, $maxWidth = null) {
$length = strlen($input);
if (!$maxWidth) {
$maxWidth = min(ceil($length / 2), 75);
}
$minWidth = min(ceil($length / 2), $maxWidth / 2);
$permutations = array();
$scores = array();
$lowestScore = 999;
$lowest = $minWidth;
foreach(range($minWidth, $maxWidth) as $width) {
$permutations[$width] = wordwrap($input, $width);
$lines = explode("\n", $permutations[$width]);
$max = 0;
foreach($lines as $line) {
$lineLength = strlen($line);
if ($lineLength > $max) {
$max = $lineLength;
}
}
$score = 0;
foreach($lines as $line) {
$lineLength = strlen($line);
$score += pow($max - $lineLength, 2);
}
$scores[$width] = $score;
if ($score < $lowestScore) {
$lowestScore = $score;
$lowest = $width;
}
}
return $permutations[$lowest];
}
С учетом ввода "как делать вещи"
выводит
How
to do
things
С учетом ввода "у Марии был маленький ягненок"
выводит
Mary had a
little lamb
Учитывая ввод "Этот очень длинный абзац был написан для демонстрации того, как программа fmt(1)
обрабатывает более длинные вводы. При тестировании вводов вы не хотите, чтобы они были слишком короткими или слишком длинными, потому что качество Программа может быть определена только после проверки сложного содержания. Быстрая коричневая лиса перепрыгивает через ленивую собаку. Конгресс не должен принимать никаких законов, касающихся установления религии или запрещающих ее свободное исповедание, или ущемляющих свободу слова или нажмите; или право народа мирно собираться и ходатайствовать перед Правительством о рассмотрении жалоб ". При максимальной ширине в 75 символов оно выдает:
This extra-long paragraph was writtin to demonstrate how the `fmt(1)`
program handles longer inputs. When testing inputs, you don't want them
be too short, nor too long, because the quality of the program can only be
determined upon inspection of complex content. The quick brown fox jumps
over the lazy dog. Congress shall make no law respecting an establishment
of religion, or prohibiting the free exercise thereof; or abridging the
freedom of speech, or of the press; or the right of the people peaceably
to assemble, and to petition the Government for a redress of grievances.