Skip to content

Instantly share code, notes, and snippets.

@ivanobulo
Created March 7, 2020 17:44
Show Gist options
  • Save ivanobulo/cd691a7c630952ed83616078abf25aad to your computer and use it in GitHub Desktop.
Save ivanobulo/cd691a7c630952ed83616078abf25aad to your computer and use it in GitHub Desktop.
def justify(words: Array[String], maxWidth: Int): Vector[String] = {
val (lines, lastWords, width) = words.foldLeft((Vector.empty[String], Vector.empty[String], 0)) {
case ((resultLines, wordAcc, currentLineLen), word) =>
if ((currentLineLen + word.length + (wordAcc.size - 1)) < maxWidth) {
(resultLines, wordAcc :+ word, currentLineLen + word.length)
} else {
val line = buildLine(wordAcc, maxWidth, currentLineLen)
(resultLines :+ line, Vector(word), word.length)
}
}
val lastLine = buildLine(lastWords, width + (lastWords.size - 1), width).padTo(maxWidth, ' ')
(lines :+ lastLine)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment