Problem overview
The previous three versions of wc counted lines, words and characters separately. This version joins them in one function, wc(lines: List<String>, mode: String): String, and the mode says which count to return. The result is always a string:
"l"gives the number of lines;"w"gives the number of words (whitespace-separated pieces);"c"gives the number of characters, the sum of the line lengths, with no newlines;"all"gives the three counts separated by tab characters: lines, words, then characters.
Any other mode, such as "x" or "L", behaves like "all". Modes are case-sensitive. This is the lesson's own simplified interface: the real tool combines flags and pads its columns with spaces.
For lines = ["hello", "world"] and mode = "all" the result is "2\t2\t10": 2 lines, 2 words and 10 characters.
Approach: count everything once, then choose
All three counts can be computed in a single pass, and the mode only decides which of them to return. The line count is the size of the list, so it needs no loop. Words and characters are totals built inside one loop. After the loop, a few if checks pick the answer.
The default case is useful: because a mode that isn't "l", "w" or "c" returns all three counts, the last line of the function doesn't test for "all" at all. Every mode that reaches it falls through to the combined result.
The lesson writes the choice as a chain of if statements that return early. Kotlin's when (mode) expression could express the same choice, with an else branch for the combined result, but the early returns keep each branch to one short line and match the steps below. Computing all three totals even when only one is asked for costs only a little extra work per line, and it keeps the function simple: there is one loop and no duplicated counting code.
Step by step
- Count the lines. Store
lines.sizein avalnamednumLines. No loop is needed. - Start the word total. A
varnamednumWordsstarts at 0. - Start the character total. A
varnamednumCharsstarts at 0. - Loop over the lines with a
forloop that names each entryline, and close its brace right away. - Trim the line into a
valnamedtrimmed, so that whitespace at the ends can't create empty pieces when splitting. - Count words, skipping blanks. If
trimmedis not empty (isNotEmpty()), add the number of pieces from splitting at runs of whitespace tonumWords. Splitting an empty string gives one empty piece, which would wrongly count as a word. - Count characters. Add
line.lengthtonumChars. It usesline, nottrimmed, because spaces are characters too. - Return the line count for
"l".toString()turns theIntinto text, since the function returns aString. - Return the word count for
"w", converted the same way. - Return the character count for
"c". - Return all three counts for every other mode, in one string with tabs between them. A string template inserts each variable into the text.
Following the loop
Take lines = [" two words ", "", "one"]. numLines is 3 before the loop starts, and the other two totals are 0. Here are the totals after each line, taken from a real run:
| after line | numWords | numChars |
|---|---|---|
" two words " | 2 | 12 |
"" | 2 | 12 |
"one" | 3 | 15 |
The first line is trimmed to "two words", which splits into two words, but it still has 12 characters because the three spaces count. The empty line changes nothing: it fails the isNotEmpty() test and its length is 0. With mode "all" the result is the three totals in order, 3, 3 and 15, with tabs between them.
The solution in Kotlin
class Solution {
fun wc(lines: List<String>, mode: String): String {
val numLines = lines.size
var numWords = 0
var numChars = 0
for (line in lines) {
val trimmed = line.trim()
if (trimmed.isNotEmpty()) { numWords += trimmed.split(Regex("\\s+")).size }
numChars += line.length
}
if (mode == "l") { return numLines.toString() }
if (mode == "w") { return numWords.toString() }
if (mode == "c") { return numChars.toString() }
return "$numLines\t$numWords\t$numChars"
}
}
Kotlin details worth noticing:
mode == "l"compares the contents of the two strings, because==in Kotlin callsequals. That is why"L"doesn't match"l".- In
"$numLines\t$numWords\t$numChars", each$nameis replaced by the variable's value, and\tis a tab character. A$followed by a name is a template, so a literal dollar sign would need to be escaped as\$. - Each
ifthat returns leaves the function immediately, so the finalreturnonly runs when none of the three matched. - Numbers are never joined to text with
+here.numLines + "\t"wouldn't compile, becauseInt.plushas no overload taking aString, while a template converts the number for you.
Edge cases and common mistakes
- Returning a number. The function's type is
String, soreturn numLinesdoesn't compile. Convert withtoString(). - Counting words in
lineinstead oftrimmed. Leading whitespace would add an empty piece to the count. - Trimming before counting characters.
" two words "has 12 characters, not 9. - Testing for
"all"only. The statement says that unknown modes behave like"all", so a check such asif (mode == "all")followed by a different default would give the wrong answer for"x". - Empty input. An empty list gives
"0"for the three single modes and"0\t0\t0"for the rest.
Testing
These results come from running the reference solution, with each tab written as <TAB>:
| lines | mode | result |
|---|---|---|
["hello", "world"] | "l" | 2 |
["hello", "world"] | "c" | 10 |
["hello", "world"] | "all" | 2<TAB>2<TAB>10 |
["hello", "world"] | "L" | 2<TAB>2<TAB>10 |
[" two words ", "", "one"] | "w" | 3 |
[" two words ", "", "one"] | "all" | 3<TAB>3<TAB>15 |
[] | "all" | 0<TAB>0<TAB>0 |
