mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-08 22:52:29 +08:00
Strutil: HammingDistance func (#197)
* Strutil: HammingDistance func The Hamming distance is the number of positions at which the corresponding symbols are different * Add hamming distance doc
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
package strutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
@@ -594,3 +595,24 @@ func SubInBetween(str string, start string, end string) string {
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// HammingDistance calculates the Hamming distance between two strings.
|
||||
// The Hamming distance is the number of positions at which the corresponding symbols are different.
|
||||
// This func returns an error if the input strings are of unequal lengths.
|
||||
func HammingDistance(a, b string) (int, error) {
|
||||
if len(a) != len(b) {
|
||||
return -1, errors.New("a length and b length are unequal")
|
||||
}
|
||||
|
||||
ar := []rune(a)
|
||||
br := []rune(b)
|
||||
|
||||
var distance int
|
||||
for i, codepoint := range ar {
|
||||
if codepoint != br[i] {
|
||||
distance++
|
||||
}
|
||||
}
|
||||
|
||||
return distance, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user