-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesarcipher.go
102 lines (87 loc) · 1.8 KB
/
caesarcipher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
"unicode"
)
var (
//fileIn = os.Stdin
testData = `C:\Users\maf\go\src\hackerrank\strings\caesarcipher\input\input00.txt`
fileIn, openErr = os.Open(testData)
fileOut = os.Stdout
rw = bufio.NewReadWriter(bufio.NewReader(fileIn), bufio.NewWriter(fileOut))
bytesWritten = 0
)
// MAIN ==================================================
func main() {
check(openErr)
defer report()
defer fileOut.Close()
defer fileIn.Close()
defer rw.Flush()
readline() //skip N
S := readline()
K := atois(readfields())[0]
write(fmt.Sprintf("%v\n", solution(S, K)))
}
// SOLUTION ==============================================
func solution(s string, rot int) (cipher string) {
for _, arune := range s {
if unicode.IsLetter(arune) {
arune = rotate(arune, rune(rot))
}
cipher += string(arune)
}
return
}
func rotate(r, amt rune) (new rune) {
start := 'A'
if unicode.IsLower(r) {
start = 'a'
}
new = ((r - start + amt) % 26) + start
return
}
// IO ====================================================
func write(s string) {
n, err := rw.WriteString(s)
check(err)
bytesWritten += n
}
func report() {
fmt.Fprintf(os.Stderr, "<wrote %v bytes>", bytesWritten)
}
func readline() (line string) {
line, err := rw.ReadString('\n')
check(err)
line = strings.TrimSpace(line)
return
}
func readfields() (fields []string) {
line, err := rw.ReadString('\n')
check(err)
fields = strings.Fields(line)
return
}
func atois(S []string) (I []int) {
I = make([]int, len(S))
for i, a := range S {
n, err := strconv.Atoi(a)
check(err)
I[i] = n
}
return
}
func check(err error) {
if err != nil {
if err.Error() == "EOF" {
fmt.Fprintln(os.Stderr, "<EOF reached>")
} else {
log.Fatal(err)
}
}
}