Text Justification and Hyphenation
Frequency: Reported
Given a string of words separated by whitespace-like characters and a line width, return the text as an array of strings, each exactly that width. No individual word is longer than the line width.
Whitespace separates words except where a hyphen joins the adjacent text into a hyphenated word.
General justification
Pack as many words as possible onto each line. Replace the gaps between words with underscores and distribute those underscores as evenly as possible. When the underscores cannot be divided evenly among the gaps, append the extra underscores at the end of the line.
For example, given:
text = "a cat is an animal"
width = 6return:
["a__cat", "is__an", "animal"]Another example:
text = "cat is an animal and so is a dog"
width = 12return:
["cat__is__an_", "animal___and", "so__is_a_dog_"]Single-word lines
If a line contains only one word, center it. When the padding cannot be split evenly, place the extra underscore at the end.
text = "human"
width = 8
result = ["_human__"]Hyphenated words
A hyphenated word stays on the current line when it fits. If the portion through the hyphen fits but the entire hyphenated word does not, split it at the hyphen. Whitespace surrounding a hyphen is normalized away.
For example:
text = "auto-complete is my go - to"
width = 8return:
["_auto-__", "complete", "is____my", "_go-to__"]The source screenshots do not preserve a function signature or numeric constraints beyond stating that no word exceeds the line width.