Skip to content

Commit

Permalink
feat: add string hamming distance algorithm (#747)
Browse files Browse the repository at this point in the history
* feat: add string hamming distance algorithm

* refactor: use only a double quote for a single package import

---------

Co-authored-by: Rak Laptudirm <[email protected]>
  • Loading branch information
alirezaazadi and raklaptudirm authored Oct 25, 2024
1 parent b9f7d55 commit e64d1f5
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
31 changes: 31 additions & 0 deletions strings/hamming/hammingdistance.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
This algorithm calculates the hamming distance between two equal length strings.
The Hamming distance between two equal-length strings of symbols is the number of positions
at which the corresponding symbols are different:
https://en.wikipedia.org/wiki/Hamming_distance
Note that we didn't consider strings as an array of bytes, therefore, we didn't use the XOR operator.
In this case, we used a simple loop to compare each character of the strings, and if they are different,
we increment the hamming distance by 1.
Parameters: two strings to compare
Output: distance between both strings */

package hamming

import "errors"

func Distance(str1, str2 string) (int, error) {
if len(str1) != len(str2) {
return -1, errors.New("strings must have a same length")
}

hammingDistance := 0
for i := 0; i < len(str1); i++ {
if str1[i] != str2[i] {
hammingDistance++
}
}

return hammingDistance, nil
}
56 changes: 56 additions & 0 deletions strings/hamming/hammingdistance_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package hamming

import "testing"

var testCases = []struct {
name string
string1 string
string2 string
expected int
}{
{
"empty strings",
"",
"",
0,
},
{
"single character strings",
"A",
"A",
0,
},
{
"two different strings with a same length",
"TestString 1",
"TestString 2",
1,
},
{
"two different strings with a different length",
"TestString1",
"TestString",
-1,
},
{
"two same strings with a same length",
"TestString",
"TestString",
0,
},
}

func TestHammingDistance(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
actual, err := Distance(tc.string1, tc.string2)
if err != nil {
if tc.expected != -1 {
t.Fatalf("Expected no error, but got %v", err)
}
} else if actual != tc.expected {
t.Errorf("Expected Hamming distance between strings: '%s' and '%s' is %v, but got: %v", tc.string1, tc.string2, tc.expected, actual)
}
})
}
}

0 comments on commit e64d1f5

Please sign in to comment.