Skip to content

Instantly share code, notes, and snippets.

@ivanobulo
Last active March 7, 2020 17:42
Show Gist options
  • Save ivanobulo/4d03f496a165ec473934fc76ee044b4b to your computer and use it in GitHub Desktop.
Save ivanobulo/4d03f496a165ec473934fc76ee044b4b to your computer and use it in GitHub Desktop.
def buildLine(words: Vector[String], maxWidth: Int, wordsWidth: Int): String = {
val spacePlacements = words.size - 1
val missingSpaces = maxWidth - wordsWidth
val numSpace = missingSpaces / Math.max(spacePlacements, 1)
val remSpaces = missingSpaces % Math.max(spacePlacements, 1)
words.zipWithIndex.foldLeft(new StringBuffer()) { case (buf, (word, pos)) =>
buf.append(word)
if (pos == 0 || pos < words.size - 1) { // first or not last
buf.append(Array.fill(numSpace + (if (pos < remSpaces) 1 else 0))(' '))
} else {
buf
}
}.toString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment