-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_test.go
More file actions
108 lines (103 loc) · 2.35 KB
/
main_test.go
File metadata and controls
108 lines (103 loc) · 2.35 KB
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
103
104
105
106
107
108
// Strings: How to calculate the hamming distance between two strings
package main
import (
"errors"
"testing"
)
// https://en.wikipedia.org/wiki/Hamming_distance:
// Τhe Hamming distance between two strings of equal length
// is the number of positions at which the corresponding symbols are different.
// In other words, it measures the minimum number of substitutions
// required to change one string into the other
//
// Hamming distance function calculates the rune based
// hamming distance between strings a and b
func HammingDistance(a string, b string) (int, error) {
// stings in Go are slices of bytes so we have first to convert them to runes
// read more here https://blog.golang.org/strings
ra := []rune(a)
rb := []rune(b)
if len(ra) != len(rb) {
return 0, errors.New("strings do not have the same length")
}
var distance int
for i := range ra {
if rb[i] != ra[i] {
distance++
}
}
return distance, nil
}
func TestHammingDistance(t *testing.T) {
tests := []struct {
name string
a string
b string
want int
wantErr bool
}{
{
name: "no equal length",
a: "abc",
b: "abcd",
want: 0,
wantErr: true,
},
{
name: "same strings ascii",
a: "abcd",
b: "abcd",
want: 0,
wantErr: false,
},
{
name: "one character different ascii",
a: "Abcd",
b: "abcd",
want: 1,
wantErr: false,
},
{
name: "all characters different ascii",
a: "ABCD",
b: "abcd",
want: 4,
wantErr: false,
},
{
name: "same strings utf8",
a: "Καλημέρα",
b: "Καλημέρα",
want: 0,
wantErr: false,
},
{
name: "one character different utf8",
a: "Καλημέρα",
b: "Καλημερα",
want: 1,
wantErr: false,
},
{
name: "all characters different utf8",
a: "ΚΑΛΗΜΕΡΑ",
b: "καλημέρα",
want: 8,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := HammingDistance(tt.a, tt.b)
if (err != nil) != tt.wantErr {
t.Errorf(
"HammingDistance(%s %s) error = %v, wantErr %v", tt.a, tt.b, err, tt.wantErr,
)
return
}
if got != tt.want {
t.Errorf("HammingDistance(%s %s) = %v, want %v", tt.a, tt.b, got, tt.want)
}
})
}
}