Skip to content

Commit 89e3a3f

Browse files
committed
feat: add string hamming distance algorithm
1 parent 495cff8 commit 89e3a3f

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

strings/hamming/hammingdistance.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
This algorithm calculates the hamming distance between two equal length strings.
3+
The Hamming distance between two equal-length strings of symbols is the number of positions
4+
at which the corresponding symbols are different:
5+
https://en.wikipedia.org/wiki/Hamming_distance
6+
7+
Note that we didn't consider strings as an array of bytes, therefore, we didn't use the XOR operator.
8+
In this case, we used a simple loop to compare each character of the strings, and if they are different,
9+
we increment the hamming distance by 1.
10+
11+
Parameters: two strings to compare
12+
Output: distance between both strings */
13+
14+
package hamming
15+
16+
import (
17+
"errors"
18+
)
19+
20+
func Distance(str1, str2 string) (int, error) {
21+
if len(str1) != len(str2) {
22+
return -1, errors.New("strings must have a same length")
23+
}
24+
25+
hammingDistance := 0
26+
for i := 0; i < len(str1); i++ {
27+
if str1[i] != str2[i] {
28+
hammingDistance++
29+
}
30+
}
31+
32+
return hammingDistance, nil
33+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package hamming
2+
3+
import "testing"
4+
5+
var testCases = []struct {
6+
name string
7+
string1 string
8+
string2 string
9+
expected int
10+
}{
11+
{
12+
"empty strings",
13+
"",
14+
"",
15+
0,
16+
},
17+
{
18+
"single character strings",
19+
"A",
20+
"A",
21+
0,
22+
},
23+
{
24+
"two different strings with a same length",
25+
"TestString 1",
26+
"TestString 2",
27+
1,
28+
},
29+
{
30+
"two different strings with a different length",
31+
"TestString1",
32+
"TestString",
33+
-1,
34+
},
35+
{
36+
"two same strings with a same length",
37+
"TestString",
38+
"TestString",
39+
0,
40+
},
41+
}
42+
43+
func TestHammingDistance(t *testing.T) {
44+
for _, tc := range testCases {
45+
t.Run(tc.name, func(t *testing.T) {
46+
actual, err := Distance(tc.string1, tc.string2)
47+
if err != nil {
48+
if tc.expected != -1 {
49+
t.Fatalf("Expected no error, but got %v", err)
50+
}
51+
} else if actual != tc.expected {
52+
t.Errorf("Expected Hamming distance between strings: '%s' and '%s' is %v, but got: %v", tc.string1, tc.string2, tc.expected, actual)
53+
}
54+
})
55+
}
56+
}

0 commit comments

Comments
 (0)