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

Boxed Sentences I

Given a sentence and a width, wrap the sentence at the width and print it inside an ASCII box.

renderBox("one two three four", 8)
+----------+
| one two  |
| three    |
| four     |
+----------+

Rules

  • Wrap greedily: keep appending words while the line stays within the width. 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.
  • Borders are +---+ (width + 2 dashes) and | … |; body lines are padded to the width. Return the picture as lines joined by "\n".

Write the wrapping as its own function, wrapWords(sentence, width), returning the lines; the grader checks it as well as renderBox.

Hints

Hint 1

Split on whitespace and accumulate greedily: start a new line only when line.length + 1 + word.length would exceed the width.

Hint 2

The punctuation rule is one extra OR in that fit check — a word matching ^[.,;:!?] is appended no matter what.

Asked at