call(back)
Algorithms & Data StructureseasySign in to star problems

Boxed Sentences II

Print several sentences in one ASCII box, each wrapped at its own width: renderMultiBox(blocks), where blocks is [{ text, width }, ...].

renderMultiBox([{ text: "one two three four", width: 8 }, { text: "a much longer sentence here", width: 16 }])
+------------------+
| one two          |
| three            |
| four             |
| ---------------- |
| a much longer    |
| sentence here    |
+------------------+

Rules

  • Wrap each block greedily at its own width: keep appending words while the line stays within the width, and never split a word — a word longer than the width gets a line of its own.
  • A line must never start with punctuation (. , ; : ! ?): a punctuation "word" joins the current line even if that overflows the width.
  • The box is as wide as the largest width: borders are +---+ (that width + 2 dashes), and every body line is | … |, padded to that width.
  • Consecutive blocks are separated by a | ---- | line whose dashes fill the inner width.
  • Return the picture as lines joined by "\n".

Hints

Hint 1

Wrap each block with one greedy loop: start a new line only when line.length + 1 + word.length would exceed that block's width and the word doesn't start with punctuation.

Hint 2

Compute the inner width once — the largest width — then pad every line to it, and emit a dashed separator before every block except the first.

Asked at