Originally described by PeterNaur.
Write a program that takes a number w, then accepts lines of text and outputs lines of text, where the output lines have as many words as possible but are never longer than w characters. Words may not be split, but you may assume that no single word is too long for a line.
See
Can this be done in vanilla-flavoured Pascal? It seems that it's necessary to allocate a vector dynamically. You may have to buffer an entire line, but you don't know w at compile time. It's been years since I've done Pascal, and was just wondering.
You can do dynamic allocation in PascalLanguage, no problem. Or just assume w will fit in a standard 255-char Pascal string.
This may be more familiar in the context of word-wrapping within a paragraph of a TextEditor. As such, it is a classic ObjectOriented problem, used as an example in the DesignPatternsBook. Even that could be seen as overkill, as this was a trivial problem even when writing a 4K AssemblyLanguage text editor.
Anyone up for TelegramProblemInManyProgrammingLanguages?
The current description of the problem does not specify if I can drop random words in the middle of input line, in order to achieve maximum number of words in output line. My reading suggests that this in fact may be the case (because the problem is described as complex and still under research). - 03/29/2014.