-
Notifications
You must be signed in to change notification settings - Fork 0
/
hamming.go
58 lines (51 loc) · 1.23 KB
/
hamming.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
package textdistance
import "errors"
// NewHamming returns a Hamming structure
func NewHamming() Hamming {
return Hamming{}
}
// Hamming structure incorporates methods for computing distance and similarity on Hamming.
type Hamming struct {
}
// Maximum returns the maximum value for Distance given two strings.
func (Hamming) Maximum(s1, s2 string) (float64, error) {
l1 := len(s1)
l2 := len(s2)
if l1 != l2 {
return 0, errors.New("strings must be of same length")
}
return float64(l1), nil
}
// Minimum returns the minimum value for Distance given two strings.
func (Hamming) Minimum(_, _ string) (float64, error) {
return 0, nil
}
// Distance returns the hamming distance
func (Hamming) Distance(s1, s2 string) (float64, error) {
l1 := len(s1)
l2 := len(s2)
if l1 != l2 {
return 0, errors.New("strings must be of same length")
}
r1 := []rune(s1)
r2 := []rune(s2)
var distance float64
for i := range r1 {
if r1[i] != r2[i] {
distance++
}
}
return distance, nil
}
// Similarity returns the hamming similarity
func (h Hamming) Similarity(s1, s2 string) (float64, error) {
d, err := h.Distance(s1, s2)
if err != nil {
return 0, err
}
m, err := h.Maximum(s1, s2)
if err != nil {
return 0, err
}
return d / m, nil
}