Start learning free

LESSON 12 OF 70 · PROJECTS: COMMAND-LINE TOOLS

wc v4 in Scala: A Mode Flag That Picks the Count

Practice Read the full explanation

Combine the previous three versions of wc. Given a list of lines and a mode flag, return the requested count(s) as a string. This is our own simplified interface, not the real wc flags: the real tool combines flags (such as -lw) and pads its columns with spaces.

Function signature:

def wc(lines: List[String], mode: String): String

Mode values:

  • "l" → line count, as a string.
  • "w" → word count (whitespace-separated tokens), as a string.
  • "c" → character count (lines only, no separating newlines), as a string.
  • "all" → lines + "\t" + words + "\t" + chars.

The "c" count is the one from v3 (the sum of the line lengths, no newlines). Any other mode value, for example "x" or "L" (modes are case-sensitive), gives the same result as "all". For an empty list, "l", "w" and "c" give "0" and "all" gives "0<TAB>0<TAB>0". The input is plain ASCII text.

Example:

Input: lines = ["hello", "world"], mode = "all"

Output: "2\t2\t10"

2 lines, 2 words (one per line), 10 characters total.


Compute all three counts in a single pass through lines, then branch on mode to pick the return value.

val numLines = lines.length
var numWords = 0
var numChars = 0
for (line <- lines) {
    val trimmed = line.trim
    if (trimmed.nonEmpty) { numWords += trimmed.split("\\s+").length }
    numChars += line.length
}
Use .toString to convert numbers to strings.

The full solution:
class Solution {
    def wc(lines: List[String], mode: String): String = {
        val numLines = lines.length
        var numWords = 0
        var numChars = 0
        for (line <- lines) {
            val trimmed = line.trim
            if (trimmed.nonEmpty) { numWords += trimmed.split("\\s+").length }
            numChars += line.length
        }
        if (mode == "l") { return numLines.toString }
        if (mode == "w") { return numWords.toString }
        if (mode == "c") { return numChars.toString }
        return s"$numLines\t$numWords\t$numChars"
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Wc V4 in Scala, explained

    Problem overview

    The last wc version combines the earlier counters. wc(lines: List[String], mode: String): String takes the lines and a mode, and returns the requested count as a string:

    • "l" gives the number of lines;
    • "w" gives the number of words;
    • "c" gives the number of characters (the sum of the line lengths, with no newlines);
    • "all" gives all three, separated by tab characters: lines, words, characters.

    Any other mode gives the same result as "all", and modes are case-sensitive, so "L" is not "l". For ["hello", "world"] with mode "all" the result is "2\t2\t10": two lines, two words and ten characters. For an empty list, "l", "w" and "c" each give "0", and "all" gives "0\t0\t0".

    Approach

    The word count and the character count both need a pass over the lines, and the line count is just the size of the list. Instead of looping once per mode, the function computes all three numbers in a single pass and only afterwards looks at mode to decide which to return. That keeps the loop free of mode checks.

    The branching comes last as a chain of early returns. Three if statements handle "l", "w" and "c". If none of them fires, execution reaches a final line that builds the combined string. That final line handles "all" and every unknown mode with no extra code, which is exactly the behaviour the statement asks for.

    Every count must be converted to a string, because the function returns a String. toString does that for an Int.

    Step by step

    1. Count the lines with lines.length in a val named numLines. No loop is needed.
    2. Create numWords as a var starting at 0.
    3. Create numChars the same way.
    4. Loop over the lines with for (line <- lines).
    5. Trim the line into trimmed, so that blank lines and surrounding spaces don't produce empty pieces when splitting.
    6. Add the words when trimmed.nonEmpty, using split("\\s+").length as in the word-counting version.
    7. Add the characters with line.length, using the original line (not the trimmed one), because spaces count as characters.
    8. Return the line count as text when the mode is "l".
    9. Return the word count as text when the mode is "w".
    10. Return the character count as text when the mode is "c".
    11. Return all three joined by tabs on the last line, which every other mode reaches.

    The solution in Scala

    class Solution {
        def wc(lines: List[String], mode: String): String = {
            val numLines = lines.length
            var numWords = 0
            var numChars = 0
            for (line <- lines) {
                val trimmed = line.trim
                if (trimmed.nonEmpty) { numWords += trimmed.split("\\s+").length }
                numChars += line.length
            }
            if (mode == "l") { return numLines.toString }
            if (mode == "w") { return numWords.toString }
            if (mode == "c") { return numChars.toString }
            return s"$numLines\t$numWords\t$numChars"
        }
    }
    

    Language details:

    • In Scala, == on strings compares their contents, so mode == "l" is the right test. There is no need for equals.
    • s"$numLines\t$numWords\t$numChars" is an interpolated string: each $name is replaced by the value, and \t is a real tab. Numbers are converted to text automatically here.
    • The early return statements leave the method at once, so the later lines run only when the earlier tests failed.
    • The word count uses "\\s+", with the backslash doubled because it sits inside a Scala string literal.

    Complexity

    The loop visits each line once. Trimming and splitting a line takes time proportional to its length, so the total time is proportional to the number of characters in the input. Only a few integers are kept, so the extra space is small, apart from the temporary array that split creates for one line at a time.

    Computing all three counts even when the mode asks for one is a deliberate trade. The extra work is small, and the function stays short: the loop does the counting and the branches only choose what to return.

    Edge cases and common mistakes

    • Returning a number. The signature says String, so return numLines would not compile. Convert with toString.
    • Counting characters from the trimmed line. That drops spaces that belong in the count.
    • Treating unknown modes as an error. The rule is that they behave like "all", and the final return gives that for free.
    • Ignoring case-sensitivity. "L" and "x" fall through to the tab-separated result.
    • Separating with spaces. The combined string uses tab characters, not spaces.

    Why the empty list works

    With an empty list the loop body never runs, so numWords and numChars keep their starting value of 0, and numLines is 0 as well. Every mode therefore returns zeros without any special case in the code. The same holds for a list of blank lines: they add to the line count, but no words are counted for them.

    Testing

    Results for List("hello", "world") with each mode (a tab is written as \t):

    ModeResult
    "l""2"
    "w""2"
    "c""10"
    "all""2\t2\t10"
    "x""2\t2\t10"
    "L""2\t2\t10"

    For an empty list with mode "all" the result is "0\t0\t0". For List(" two words ", "", "a") with "all" it is "3\t3\t13": three lines, three words, and 13 characters (12 + 0 + 1) because the surrounding spaces are counted.

    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free