Created
January 26, 2024 20:16
-
-
Save kubikowski/cdcafcb1031f109f59ebd9ccbb006007 to your computer and use it in GitHub Desktop.
[TypeScript] Levenshtein Distance
This file contains 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
/** | |
* This is a simple and performant implementation of | |
* the Wagner–Fischer algorithm for computing | |
* the Levenshtein Distance between two strings. | |
* | |
* It is based on the observation that we can reserve a matrix | |
* to hold the Levenshtein distances between all prefixes of | |
* the first string and all prefixes of the second. | |
* | |
* Then we can compute the values in the matrix | |
* by flood filling the matrix, and thus find the distance | |
* between the two full strings as the last value computed. | |
*/ | |
export function levenshteinDistance(first: string, second: string): number { | |
const dist: number[][] = []; | |
for (let i = 0; i <= first.length; i++) { | |
dist[i] = [i]; | |
} | |
for (let j = 0; j <= second.length; j++) { | |
dist[0][j] = j; | |
} | |
for (let i = 1; i <= first.length; i++) { | |
for (let j = 1; j <= second.length; j++) { | |
const comparativeDistance = first[i - 1] === second[j - 1] ? 0 : 1; | |
const minAdjacentDistance = Math.min( | |
dist[i - 1][j - 1], | |
dist[i - 1][j], | |
dist[i][j - 1] | |
); | |
dist[i][j] = minAdjacentDistance + comparativeDistance; | |
} | |
} | |
return dist[first.length][second.length]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment