Skip to content

Commit 9270ca6

Browse files
authored
Merge pull request #183 from kucinghitam13/master
Add simple caesar cipher using go
2 parents 16942ae + f6f9fa5 commit 9270ca6

File tree

2 files changed

+99
-0
lines changed

2 files changed

+99
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package crypto
2+
3+
import (
4+
"strings"
5+
)
6+
7+
// CaesarCipherEncode ...
8+
func CaesarCipherEncode(input string, shift int) string {
9+
var output strings.Builder
10+
for _, c := range input {
11+
var lowercaseFlag bool
12+
if c >= 97 && c <= 122 {
13+
c -= 32
14+
lowercaseFlag = true
15+
}
16+
if c >= 65 && c <= 90 {
17+
c += rune(shift)
18+
if c > 90 {
19+
c = 65 + (c-90-1)%26
20+
} else if c < 65 {
21+
c = 90 - (65-c-1)%26
22+
}
23+
}
24+
if lowercaseFlag {
25+
c += 32
26+
}
27+
output.WriteRune(c)
28+
}
29+
return output.String()
30+
}
31+
32+
// CaesarCipherDecode ...
33+
func CaesarCipherDecode(input string, shift int) string {
34+
return CaesarCipherEncode(input, -shift)
35+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package crypto
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
func Test_CaesarCipherEncode(t *testing.T) {
9+
tests := []struct {
10+
name string
11+
input string
12+
shift int
13+
expected string
14+
}{
15+
{
16+
name: "Encode 1",
17+
input: "A quIck BrOwN FoX jUMps OvEr thE lAzY DoG 123",
18+
shift: 3,
19+
expected: "D txLfn EuRzQ IrA mXPsv RyHu wkH oDcB GrJ 123",
20+
},
21+
{
22+
name: "Encode 2",
23+
input: "A quIck BrOwN FoX jUMps OvEr thE lAzY DoG 123",
24+
shift: -3,
25+
expected: "X nrFzh YoLtK ClU gRJmp LsBo qeB iXwV AlD 123",
26+
},
27+
}
28+
for _, tt := range tests {
29+
t.Run(tt.name, func(t *testing.T) {
30+
if got := CaesarCipherEncode(tt.input, tt.shift); !reflect.DeepEqual(got, tt.expected) {
31+
t.Errorf("CaesarCipherEncode() = %v, expected %v", got, tt.expected)
32+
}
33+
})
34+
}
35+
}
36+
37+
func Test_CaesarCipherDecode(t *testing.T) {
38+
tests := []struct {
39+
name string
40+
input string
41+
shift int
42+
expected string
43+
}{
44+
{
45+
name: "Decode 1",
46+
input: "D txLfn EuRzQ IrA mXPsv RyHu wkH oDcB GrJ 123",
47+
shift: 3,
48+
expected: "A quIck BrOwN FoX jUMps OvEr thE lAzY DoG 123",
49+
},
50+
{
51+
name: "Decode 2",
52+
input: "X nrFzh YoLtK ClU gRJmp LsBo qeB iXwV AlD 123",
53+
shift: -3,
54+
expected: "A quIck BrOwN FoX jUMps OvEr thE lAzY DoG 123",
55+
},
56+
}
57+
for _, tt := range tests {
58+
t.Run(tt.name, func(t *testing.T) {
59+
if got := CaesarCipherDecode(tt.input, tt.shift); !reflect.DeepEqual(got, tt.expected) {
60+
t.Errorf("CaesarCipherDecode() = %v, expected %v", got, tt.expected)
61+
}
62+
})
63+
}
64+
}

0 commit comments

Comments
 (0)