A full Knuth-Plass implementation showing dynamic programming for optimal line breaks, badness calculation, fitness classification, and typography river detection.
The Knuth-Plass algorithm finds the optimal line breaks by treating text layout as a dynamic programming problem. It evaluates all possible break points and chooses the sequence that minimizes total "badness" — a measure of how far each line deviates from the ideal inter-word spacing.
Badness formula: (slack / lineWidth)³ × 1000 — cubic
penalty that heavily disfavors very tight or very loose lines.
Penalties: River gaps (+5000 when spaces align vertically), tight lines (+3000), and hyphenation (+50) all increase badness.
Fitness classification: Lines are categorized as tight (≤65% stretch), decent, loose (100-150%), or very loose (>150%, indicating potential rivers).