Start learning free

LESSON 380 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v2 — Count Adjacent Runs in Go

Practice

Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.

Each output line is formatted as fmt.Sprintf("%7d ", count) + value: a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

func uniqCount(lines []string) string

Example:

Input: lines = ["a", "a", "b", "c", "c", "c"]

Output (when printed):
      2 a
      1 b
      3 c

The first run is two "a"s, then a single "b", then three "c"s — three output lines.


Track prev and count. When a NEW value arrives (or you reach the end), flush the previous run. Use fmt.Sprintf("%7d ", count) to right-align the count, then concat the line.

if count > 0 {
    result = append(result, fmt.Sprintf("%7d ", count)+prev)
}
Don't forget to flush after the loop ends. The strings package provides strings.Join(result, "\n").

The full solution:
func uniqCount(lines []string) string {
    result := []string{}
    count := 0
    prev := ""
    for i := 0; i < len(lines); i++ {
        if count > 0 && lines[i] == prev {
            count++
        } else {
            if count > 0 {
                result = append(result, fmt.Sprintf("%7d ", count)+prev)
            }
            prev = lines[i]
            count = 1
        }
    }
    if count > 0 {
        result = append(result, fmt.Sprintf("%7d ", count)+prev)
    }
    return strings.Join(result, "\n")
}

STEP 1 OF 13
    Ctrl + Enter to check

    Uniq V2 in Go

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