object WordWrap {
def formatLines(words: List[String], maxWidth: Int): List[String] = {
var result = List.empty[String]
var currentLine = ""
var currentLength = 0
for (word <- words) {
val wordLen = word.length
// If adding this word exceeds maxWidth, push current line
if (currentLength + (if (currentLine.isEmpty) 0 else 1) + wordLen > maxWidth) {
if (currentLine.nonEmpty) {
result = result :+ currentLine
}
currentLine = word
currentLength = wordLen
} else {
if (currentLine.nonEmpty) {
currentLine += " "
currentLength += 1
}
currentLine += word
currentLength += wordLen
}
}
// Push the last line if not empty
if (currentLine.nonEmpty) {
result = result :+ currentLine
}
result
}
def main(args: Array[String]): Unit = {
val words = List("This", "is", "a", "programming", "example", "of", "text", "wrapping")
val maxWidth = 12
val lines = formatLines(words, maxWidth)
for (line <- lines) {
println(s""""$line"""")
}
}
}
/*
run:
"This is a"
"programming"
"example of"
"text"
"wrapping"
*/