Skip to content

Commit e64d1f5

Browse files
feat: add string hamming distance algorithm (#747)
* feat: add string hamming distance algorithm * refactor: use only a double quote for a single package import --------- Co-authored-by: Rak Laptudirm <[email protected]>
1 parent b9f7d55 commit e64d1f5

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

strings/hamming/hammingdistance.go

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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 "errors"
17+
18+
func Distance(str1, str2 string) (int, error) {
19+
if len(str1) != len(str2) {
20+
return -1, errors.New("strings must have a same length")
21+
}
22+
23+
hammingDistance := 0
24+
for i := 0; i < len(str1); i++ {
25+
if str1[i] != str2[i] {
26+
hammingDistance++
27+
}
28+
}
29+
30+
return hammingDistance, nil
31+
}
+56
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)