Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add string hamming distance algorithm #747

Merged
merged 4 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
})
}
}
Loading