Created
March 7, 2020 17:44
-
-
Save ivanobulo/cd691a7c630952ed83616078abf25aad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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