in reply to Puzzle: need a more general algorithm
Take a look at Knuth's TeX language. This is pretty close to the "line length" issue that gets solved for every paragraph set by his typesetting system. And if anyone has a good general algorithm for doing this,
it's got to be Knuth!
In Section
Seekers of Perl Wisdom