Problem overview
The real cat command takes several files and prints them one after another. This version models that with a function, concatCat, that receives allLines: List[List[String]]: a list of "files", where each file is itself a list of lines. The function flattens all the lines in order and joins them with newlines.
For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". A file can be empty, in which case it adds no lines, and the list can hold no files at all, in which case the result is an empty string.
Approach
The input has two levels: files, and lines inside each file. The output has one level: a single sequence of lines. The job is to flatten the two levels into one, keeping the order, and then use mkString("\n") to join, as in the first version.
The flattening is a nested loop. The outer loop visits the files in order. For each file, the inner loop visits its lines in order and appends each to one growing buffer. Because the files are visited in order and each file's lines are visited in order, the buffer ends up with every line in the order cat would print them.
An empty file never enters its inner loop, so it adds nothing. An empty list of files never enters the outer loop, so the buffer stays empty and mkString on an empty buffer returns "".
Join once at the end, over the flat buffer. That is what keeps the separators correct: newlines appear only between lines of the final sequence, however the lines were spread over files.
Step by step
- Create the buffer.
flatis an emptyscala.collection.mutable.ArrayBuffer[String](), a list that can grow. It will hold every line of every file, with no lists inside it. - Loop over the files with
for (fileLines <- allLines). EachfileLinesis aList[String]. - Loop over that file's lines with
for (line <- fileLines), nested inside the first loop. - Add the line to the buffer with
flat += line. - Join after both loops and return
flat.mkString("\n").
The solution in Scala
class Solution {
def concatCat(allLines: List[List[String]]): String = {
val flat = scala.collection.mutable.ArrayBuffer[String]()
for (fileLines <- allLines) {
for (line <- fileLines) {
flat += line
}
}
return flat.mkString("\n")
}
}
Details worth knowing:
- The buffer is a
val, yet it grows.valmeans the nameflatcan't be pointed at another object, but anArrayBufferis a mutable collection, so+=changes it in place. A plainListcan't change, which is why the lesson uses a buffer. - The full name
scala.collection.mutable.ArrayBufferis written out because Scala's default collections are the immutable ones. A bareArrayBufferwould need an import. - Inside the buffer's
[String]the element type is fixed, so adding aList[String]instead of aStringwould not compile. - The loops use
for (x <- collection), which runs its body once per element and gives the element a name.
A shorter way to write it
A list of lists has a flatten method that does the two nested loops for you:
allLines.flatten.mkString("\n")
With [["hello", "world"], ["foo", "bar", "baz"]] it gives "hello\nworld\nfoo\nbar\nbaz", and with an empty list of files it gives "". The lesson builds the buffer by hand so that the structure of the nested loop is explicit.
Edge cases and common mistakes
- No files.
List()gives"". - Only empty files.
List(List(), List())also gives"", because no line ever reaches the buffer. - An empty file between others.
List(List(), List("x"), List())gives"x". The empty files contribute nothing, not even a newline. - Joining each file first. Calling
mkString("\n")on every file and then joining those strings with another newline puts an empty string into the outer join for each empty file.List(List("a"), List(), List("b"))gives"a\n\nb"that way, with a blank row that no file contained. Flatten first and join once. - Forgetting the order. The result must keep the files in the order given, each file's lines in their own order. Sorting or reversing anywhere breaks that.
- A trailing newline. Appending
"\n"after every line would leave an extra one at the end. Joining withmkStringavoids it.
Testing
| Input | Result |
|---|---|
List(List("hello", "world"), List("foo", "bar", "baz")) | "hello\nworld\nfoo\nbar\nbaz" |
List(List(), List("x"), List()) | "x" |
List(List(), List()) | "" |
List() | "" |
