Start learning free

LESSON 388 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: tr v2 — Set Translation in Go

Practice

Build a more powerful version of the Unix tr command. Given a list of lines and two equal-length strings set1 and set2, replace every character in each line that appears in set1 at index i with set2[i]. Characters not in set1 are unchanged. Return the lines joined by newline characters (\n).

Notes: set1 and set2 have the same length, contain only ASCII characters, and set1 has no repeated character. Characters are taken literally: there are no ranges like a-z. All replacements happen at once, so set1 = "ab", set2 = "ba" swaps the two letters. Lines may be empty.

Function signature:

func tr(lines []string, set1 string, set2 string) string

Example:

Input: lines = ["banana", "cherry"], set1 = "abc", set2 = "ABC"

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Build a map[byte]byte from each byte of set1 to the matching byte of set2. Then walk each line byte-by-byte and translate via the map, leaving unmapped bytes unchanged.

m := make(map[byte]byte)
for i := 0; i < len(set1); i++ {
    m[set1[i]] = set2[i]
}
// per byte: if v, ok := m[ch]; ok { ... } else { ... }


The full solution:
func tr(lines []string, set1 string, set2 string) string {
    m := make(map[byte]byte)
    for i := 0; i < len(set1); i++ {
        m[set1[i]] = set2[i]
    }
    result := []string{}
    for i := 0; i < len(lines); i++ {
        out := ""
        for j := 0; j < len(lines[i]); j++ {
            ch := lines[i][j]
            if v, ok := m[ch]; ok {
                out += string(v)
            } else {
                out += string(ch)
            }
        }
        result = append(result, out)
    }
    return strings.Join(result, "\n")
}

STEP 1 OF 15
    Ctrl + Enter to check

    Tr 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