Problem overview
This version adds the -n flag of cat as a new function, numberedCat. It takes a List[String] and returns the lines joined with newlines, each one preceded by its 1-based number. The number is right-aligned in a field 6 characters wide, followed by a tab character and then the line text. Blank lines are numbered too, and an empty list gives an empty string.
For ["hello", "world", "foo"] the result is " 1\thello\n 2\tworld\n 3\tfoo". Each number is padded with spaces on the left until it is 6 characters wide, so 1 is preceded by five spaces.
Approach
Two things are needed for each row: the line's position and the line. Looping over lines.indices gives the positions 0, 1, 2 and so on, and lines(i) gives the line at a position. The number shown is i + 1, because people count lines from 1 while Scala counts positions from 0.
For the row layout, Scala strings have a format method that works like C's printf: a pattern with placeholders, followed by the values. In "%6d\t%s", %6d prints an integer in a field 6 characters wide (padding on the left), \t is a tab, and %s prints a string.
The rows must be separated by newlines, but without a newline at the end. The loop therefore adds a newline before every row except the first. A StringBuilder collects the pieces, which is cheaper than creating a new string for every concatenation.
Step by step
- Create a
StringBuildernamedsbto hold the output. - Loop over the positions with
for (i <- lines.indices), since both the number and the line are needed. - Check
i > 0. Only rows after the first need a separator in front of them. - Append a newline inside that check.
- Append the row. Format
i + 1andlines(i)with the pattern"%6d\t%s". Scala indexes a list with round brackets. - Return the text with
sb.toString(), after the loop.
The solution in Scala
class Solution {
def numberedCat(lines: List[String]): String = {
val sb = new StringBuilder()
for (i <- lines.indices) {
if (i > 0) {
sb.append("\n")
}
sb.append("%6d\t%s".format(i + 1, lines(i)))
}
return sb.toString()
}
}
Details worth knowing:
"%6d\t%s".format(i + 1, lines(i))callsformaton the pattern string, and the values after it fill the placeholders in order.%dneeds an integer and%stakes any value as text.- The width in
%6dis a minimum. A number with more than 6 digits is not cut:"%6d\t%s".format(1234567, "wide")gives"1234567\twide". lines.indicesis a range of the valid positions,0 until lines.size. For an empty list it is empty, so the loop body never runs.lines(i)on aListwalks from the head to positioni, so a long list is slower to index than an array. For lines read from a file this is fine for learning.
Edge cases and common mistakes
- Starting the number at 0. Using
iinstead ofi + 1numbers the first line 0. - A newline after the last row. Appending the newline after every row, instead of before every row but the first, leaves a trailing
\n. - Blank lines. They are numbered like any other:
List("a", "", "b")gives" 1\ta\n 2\t\n 3\tb", where row 2 is just the number and the tab. - Empty list. The loop never runs and the result is
"". - Wrong alignment. Number padding comes from the format width. Using
%-6dwould left-align instead.
Testing
| Input | Result |
|---|---|
List("hello", "world", "foo") | " 1\thello\n 2\tworld\n 3\tfoo" |
List("a", "", "b") | " 1\ta\n 2\t\n 3\tb" |
List() | "" |
With ten lines x1 to x10, the last row is " 10\tx10": four spaces, then the number.
