Tour of Go exercise: rot13Reader

EDIT:

Basically your solution is good and works, you just mistyped 1 character:

case x >= 110 && x >= 122:

Change it to:

case x >= 110 && x <= 122:

Your input and output:

Lbh penpxrq gur pbqr!
You prnpxrq tur poqr!

There is change in every word. The problem is not that only the first word is read and decoded, the problem is in your decoding algorithm.

In ROT13 if shifting goes outside of the letter range, you have to start from the beginning of the alphabet (or at the end). For example shifting 'N' would be 'Z' + 1, so it becomes 'A', the first letter. See this simple character mapping:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm

So what you should do is after shifting by 13, if the letter goes outside of the alphabet, shift it by -26 (number of letters in the English alphabet) which has the desired effect (that after the last letter you continued from the first).

An example solution:

func rot13(x byte) byte {
    capital := x >= 'A' && x <= 'Z'
    if !capital && (x < 'a' || x > 'z') {
        return x // Not a letter
    }

    x += 13
    if capital && x > 'Z' || !capital && x > 'z' {
        x -= 26
    }
    return x
}

And its output:

You cracked the code!

Try it on the Go Playground.


You could also use instead:

func rot13(x byte) byte {
    input := []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
    output := []byte("NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")
    match := bytes.Index(input, []byte{x})
    if match == -1 {
        return x
    }
    return output[match]
}

The problem is that your function does not work as you want. To verify this, just try to run your function on "Lbh penpxrq Lbh gur pbqr!". As you see first word is decoded (as well as the third one). So this means that your function does not run only on the first word, but in fact runs on all the words (it just happened that nothing else is changed).

func (rot *rot13Reader) Read(p []byte) (n int, err error) {
    n, err = rot.r.Read(p)
    for i := 0; i < len(p); i++ {
        if (p[i] >= 'A' && p[i] < 'N') || (p[i] >='a' && p[i] < 'n') {
            p[i] += 13
        } else if (p[i] > 'M' && p[i] <= 'Z') || (p[i] > 'm' && p[i] <= 'z'){
            p[i] -= 13
        }
    }
    return
}

And here is a Playground. Code is taken from here.

Tags:

Go