Cannot decode Caesar-Encrypted messages

94 Views Asked by At

I have to write a function for school that decodes Caesar-Encrypted messages. Our teacher gave us the code that encodes the messages, and asked us to write one based on the givenb function that decodes any encrypted message. (The key/shift wasn't given but was explicitly not 3 as in the the encode example, we should figure out ourselves. With online tools i know the key is 17 but for the purpose ofthe question i chose the given example with the known shift of 3)

The given Function with the Shift 3:

func main () {
    var textN string = "Wenn man jetzt diesen Text Cäsar-Codieren möchte, dann macht man das so!" // Variable was given by tacher
    var textC string = "Zhqq pdq mhwdw glhvhq Whbw Fävdu-Frglhuhq pöfkwh, gdqq pdfkw pdq gdv vr!" // Variable was given by tacher
    fmt.Println(textN)
    encode(textN)
    decode(textC)
}

// The given Function with the shift 3:

func encode (text string){
        var ergebnis string
        for _,w:=range(text){
                if w>='A' && w<='Z' {
                    if w+3>'Z'{
                        ergebnis += string((w+3)-'Z'+'A')
                    } else {
                        ergebnis += string(w+3)
                    }
                } else if  w>='a' && w<='z'{
                    if w+3>'z' {
                        ergebnis += string((w+3)-'z'+'a')
                    } else {
                        ergebnis += string(w+3)
                    }
                } else {
                    ergebnis += string(w)
                }
            }
        fmt.Println(ergebnis)
}

// My decode funtion with the "backwards shift" 3:

func decode (text string) {
    var ergebnis string
    for _,w:=range(text){
        if w >='A' && w <='Z' {
            if w-3 < 'A' {
                // fmt.Println(string(w-3)) // Search for Mistakes made by me
                ergebnis += string((w-3)+'Z'-'A')
            } else {
                // fmt.Println(string(w-3)) // Search for Mistakes made by me
                ergebnis += string(w-3)
            }
        } else if  w>='a' && w<='z'{
            if w-3 < 'a' {
                // fmt.Println(string(w-3)) // Search for Mistakes made by me
                ergebnis += string((w-3)+'z'-'a')
            } else {
                // fmt.Println(string(w-3)) // Search for Mistakes made by me
                ergebnis += string(w-3)
            }
        } else{
            ergebnis += string(w)
        }
    }
    fmt.Println(ergebnis)
}

Now the problem is: textN isn't equal to decode(textC), my code seems to fail at lowercase letters that shifted back 3 letters don't become the decoded letters they should be. I saw this at "z" and "x" and i dont have a clue why. I tried highering/lowering the shift but that didn't work, changed plusses and minusses and bigger lower signs. I don't know what to try and am thankful in advance.

1

There are 1 best solutions below

1
On

there is one solution you can use, i can provide other slower one, but more interesting if you want.

func Chipher(input string, shift int) string {
    bts := []rune(input)
    var cursor *rune
    // i em using it like this to remove repetition but its little advanced
    // it may make you suspicious to teacher
    shiftFn := func(start, end rune) bool {
        r := *cursor
        // not in range we cannot shift it
        if r < start || r > end {
            return false
        }

        res := start + (r-start+rune(shift))%(end-start)
        if res < start {
            res += end - start + 1
        }
        *cursor = res

        return true
    }

    for i := range bts {
        cursor = &bts[i]
        // this is little trick, if one of expresions returns true, expressions
        // after will not get executed as result would be true anyway
        _ = shiftFn('a', 'z') || shiftFn('A', 'Z') || shiftFn('0', '9')
    }

    return string(bts)
}

now this is all beautiful but we have to do tests as well

func TestChipher(t *testing.T) {
    testCases := []struct {
        desc          string
        input, output string
        shift         int
    }{
        {
            desc:   "simple shift",
            input:  "abcd",
            shift:  1,
            output: "bcde",
        },
        {
            desc:   "negative shift",
            input:  "abcd",
            shift:  -1,
            output: "zabc",
        },
        {
            desc:   "numbers",
            input:  "0123",
            shift:  1,
            output: "1234",
        },
        {
            desc:   "capital letters",
            input:  "ABCD",
            shift:  1,
            output: "BCDE",
        },
        {
            desc:   "big shift",
            input:  "ABCD",
            shift:  1000,
            output: "ABCD",
        },
    }
    for _, tC := range testCases {
        t.Run(tC.desc, func(t *testing.T) {
            res := Chipher(tC.input, tC.shift)
            if res != tC.output {
                t.Errorf("\n%s :result\n%s :expected", res, tC.output)
            }
        })
    }
}

hope you will learn new things from this