Problem overview
The second version of the uniq project adds the -c flag. The function uniqCount(_ lines: [String]) -> String collapses each run of adjacent equal lines into one output line that shows the run's length followed by the value. Each output line is String(format: "%7d ", count) + value: the count right-aligned in 7 characters, one space, then the line itself. The output lines are joined with \n.
For ["a", "a", "b", "c", "c", "c"] the runs are two a lines, one b and three c lines, so the output has three lines:
2 a
1 b
3 c
Version 1 only had to decide whether to keep a line. Now the function must remember how long the current run is, which takes two variables that describe the run in progress.
Approach
A run is written out when it ends, and it ends when a different line arrives. So the loop tracks the current run with two variables: prev, the text of the run, and count, how many lines it has so far. For each new line there are two cases:
- If a run is going and the line equals
prev, the run grows: add 1 tocount. - Otherwise the old run is over. Write its output line, if there was a run, then start a new run with this line and a count of 1.
Two details need care. Before the first line there is no run, which is why count starts at 0 and the inner test count > 0 guards the write: with no run yet, there is nothing to write. And the last run has no following line to end it, so the loop never writes it. After the loop, the same write has to happen once more.
For the example, the state after each line is:
| After line | prev | count | Output lines written so far |
|---|---|---|---|
"a" (index 0) | "a" | 1 | 0 |
"a" (index 1) | "a" | 2 | 0 |
"b" (index 2) | "b" | 1 | 1 |
"c" (index 3) | "c" | 1 | 2 |
"c" (index 4) | "c" | 2 | 2 |
"c" (index 5) | "c" | 3 | 2 |
When the loop ends, the run of three c lines is still open with only two output lines written. The final write adds the third.
Step by step
- Create
result, an empty array of strings, withvar. It will hold one output line per run. - Create
countas avarstarting at 0. The value 0 means no run has started. - Create
prevas avarset to"". It will remember which line the current run is made of. - Loop over the positions with
for i in 0..<lines.count, writing the closing brace right away. - Test for a continuing run. Write
if count > 0 && lines[i] == prev, followed by itselse. Both conditions must hold: a run exists, and this line matches it. - Extend the run in the
ifbranch by adding 1 tocount. - Detect a finished run. In the
elsebranch a different line has arrived, so the run before it is over. An innerif count > 0checks that a run was actually going, which is false only for the very first line. - Write the finished run. Inside that inner
if, appendString(format: "%7d ", count) + prevtoresult.%7dis a whole number padded with spaces on the left to width 7, and the space after it is part of the format. - Start the next run after the inner
if: setprevtolines[i]. The line that ended the old run is the first line of the new one. - Set
countto 1 for the new run. - Handle the open run. After the loop, write the same test,
if count > 0. This one is outside the loop. - Write the last run inside it, with the same format.
- Join and return with
result.joined(separator: "\n").
The solution in Swift
func uniqCount(_ lines: [String]) -> String {
var result = [String]()
var count = 0
var prev = ""
for i in 0..<lines.count {
if count > 0 && lines[i] == prev {
count += 1
} else {
if count > 0 {
result.append(String(format: "%7d ", count) + prev)
}
prev = lines[i]
count = 1
}
}
if count > 0 {
result.append(String(format: "%7d ", count) + prev)
}
return result.joined(separator: "\n")
}
The details a learner might trip on:
String(format:)comes from Foundation. It follows theprintfstyle.%7dworks with anIntargument, andString(format: "%7d ", 42)is five spaces,42and one trailing space. The separating space is part of the format string, so it sits before the value.- Width, not a limit. A count that needs more than 7 digits isn't cut: a run of 12,345,678 lines gives
12345678 z, with one space and no padding. - A blank first line is an ordinary value. With
["", "", "a"]the output is two runs: a run of 2 blank lines and a run of 1a. The starting valueprev = ""doesn't get in the way, because the guard in front of the write iscount > 0, which is false until a run has started. - The
elsebranch does two jobs. It closes the old run, which may not exist, and opens the new one. Both jobs belong there because a different line ends one run and begins another at once.
Complexity
Time is O(n) in the total number of characters: each line is compared once with prev, and each run is formatted once. Extra space is the array of output lines plus the joined string, which is at most proportional to the input size.
Edge cases and common mistakes
- Forgetting the last run. Without the code after the loop, the output for the example loses its
cline and ends afterb. - Empty input.
[]gives"": the loop doesn't run,countis still 0 and the final write is skipped. - A single line.
["x"]gives" 1 x", six spaces and a 1, then a space andx. - Non-adjacent repeats are separate runs.
["a", "b", "a"]gives three output lines, each with a count of 1. - Blank lines are values.
[""]gives" 1 ", the count, then a space, then nothing. - Wrong width. Using
%dinstead of%7d, or dropping the space after it, changes the text and the lesson's tests fail.
Testing
| lines | Result |
|---|---|
["a", "a", "b", "c", "c", "c"] | " 2 a\n 1 b\n 3 c" |
["", "", "a"] | " 2 \n 1 a" |
["a", "b", "a"] | " 1 a\n 1 b\n 1 a" |
["x"] | " 1 x" |
[] | "" |
