Skip to content
This repository has been archived by the owner on Mar 2, 2024. It is now read-only.

Commit

Permalink
perf: better damerau levenshtein
Browse files Browse the repository at this point in the history
  • Loading branch information
gustaveWPM committed Mar 2, 2024
1 parent 9e1b5a0 commit 28bb63b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 18 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
"editor.formatOnPaste": true,
"editor.wordWrap": "on",
"editor.codeActionsOnSave": {
"source.organizeImports": true
"source.organizeImports": "explicit"
}
}
31 changes: 14 additions & 17 deletions src/dev/math/DamerauLevenshtein.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
export function damerauLevenshtein(s1: string, s2: string): number {
const s1len = s1.length;
const s2len = s2.length;
function damerauLevenshtein(s1: string, s2: string): number {
if (s1 === s2) return 0;

const [s1len, s2len] = [s1.length, s2.length];
const matrix: number[][] = Array.from({ length: s1len + 1 }, () => new Array(s2len + 1).fill(0));

for (let i: number = 1; i <= s1len; i++) {
matrix[i][0] = i;
}
for (let y = 1; y <= s1len; y++) matrix[y][0] = y;
for (let x = 1; x <= s2len; x++) matrix[0][x] = x;

for (let j: number = 1; j <= s2len; j++) {
matrix[0][j] = j;
}

for (let i: number = 1; i <= s1len; i++) {
for (let j: number = 1; j <= s2len; j++) {
if (s1[i - 1] === s2[j - 1]) {
matrix[i][j] = matrix[i - 1][j - 1];
for (let y = 1; y <= s1len; y++) {
for (let x = 1; x <= s2len; x++) {
if (s1[y - 1] === s2[x - 1]) {
matrix[y][x] = matrix[y - 1][x - 1];
} else {
matrix[i][j] = 1 + Math.min(matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]);
if (i > 1 && j > 1 && s1[i - 1] === s2[j - 2] && s1[i - 2] === s2[j - 1]) {
matrix[i][j] = Math.min(matrix[i][j], matrix[i - 2][j - 2] + 1);
matrix[y][x] = 1 + Math.min(matrix[y - 1][x], matrix[y][x - 1], matrix[y - 1][x - 1]);
if (y > 1 && x > 1 && s1[y - 1] === s2[x - 2] && s1[y - 2] === s2[x - 1]) {
matrix[y][x] = Math.min(matrix[y][x], matrix[y - 2][x - 2] + 1);
}
}
}
}

return matrix[s1len][s2len];
}

Expand Down

0 comments on commit 28bb63b

Please sign in to comment.