Last active
May 11, 2024 08:06
-
-
Save orimdominic/dfc53c89057a01eaace49dd5f97ec034 to your computer and use it in GitHub Desktop.
Go Tour Exercises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"os" | |
"strings" | |
) | |
type rot13Reader struct { | |
r io.Reader | |
} | |
func (rot rot13Reader) Read(b []byte) (int, error) { | |
n, err := rot.r.Read(b) // this is what will be returned | |
if err != nil { | |
return 0, err | |
} | |
// got this from the linked Wkipedia article | |
input := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" | |
output := "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" | |
// build a map from `input` and `output` | |
inpOutMap := make(map[byte]byte) | |
for i := range input { | |
inpOutMap[input[i]] = output[i] | |
} | |
for i, c := range b { | |
mappedChar, ok := inpOutMap[c] | |
if !ok { | |
b[i] = c | |
continue | |
} | |
b[i] = mappedChar | |
} | |
return n, nil | |
} | |
func main() { | |
s := strings.NewReader("Lbh penpxrq gur pbqr!") | |
r := rot13Reader{s} | |
io.Copy(os.Stdout, &r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment