Last active
September 23, 2025 17:22
-
-
Save wjkoh/61f3ad63283a06a865f1ca42713383e5 to your computer and use it in GitHub Desktop.
Go: Levenshtein Distance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import "golang.org/x/text/unicode/norm" | |
| type levenshteinDistancer struct { | |
| deletionCost int | |
| insertionCost int | |
| substitutionCost int | |
| } | |
| func NewLevenshteinDistancer(deletion, insertion, substitution int) *levenshteinDistancer { | |
| return &levenshteinDistancer{ | |
| deletionCost: deletion, | |
| insertionCost: insertion, | |
| substitutionCost: substitution, | |
| } | |
| } | |
| func (l *levenshteinDistancer) Distance(source string, target string) int { | |
| // Text normalization for CJK languages. You can remove them safely. | |
| source = norm.NFD.String(source) | |
| target = norm.NFD.String(target) | |
| return l.distance([]rune(source), []rune(target)) | |
| } | |
| func (l *levenshteinDistancer) distance(source []rune, target []rune) int { | |
| prevRow := make([]int, len(source)+1) | |
| // The first row represents the cost of transforming prefixes of the source string into an empty string. The only | |
| // available operation is deletion. | |
| for i := 1; i < len(prevRow); i++ { | |
| prevRow[i] = prevRow[i-1] + l.deletionCost | |
| } | |
| currRow := make([]int, len(prevRow)) | |
| for _, r := range target { | |
| // The first element of the current row is the cost of transforming an empty string into the target string's current | |
| // prefix. The only available operation is insertion. | |
| currRow[0] = prevRow[0] + l.insertionCost | |
| for i := 1; i < len(currRow); i++ { | |
| substitutionCost := l.substitutionCost | |
| if source[i-1] == r { | |
| substitutionCost = 0 | |
| } | |
| currRow[i] = min( | |
| currRow[i-1]+l.deletionCost, // deletion | |
| prevRow[i]+l.insertionCost, // insertion | |
| prevRow[i-1]+substitutionCost, // substitution | |
| ) | |
| } | |
| prevRow, currRow = currRow, prevRow | |
| } | |
| return prevRow[len(prevRow)-1] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment