Last change
on this file since ceaed42 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1.0 KB
|
Line | |
---|
1 | export function levenshtein(a, b) {
|
---|
2 | if (a.length === 0)
|
---|
3 | return b.length;
|
---|
4 | if (b.length === 0)
|
---|
5 | return a.length;
|
---|
6 | const matrix = [];
|
---|
7 | let i;
|
---|
8 | for (i = 0; i <= b.length; i++) {
|
---|
9 | matrix[i] = [i];
|
---|
10 | }
|
---|
11 | let j;
|
---|
12 | for (j = 0; j <= a.length; j++) {
|
---|
13 | matrix[0][j] = j;
|
---|
14 | }
|
---|
15 | for (i = 1; i <= b.length; i++) {
|
---|
16 | for (j = 1; j <= a.length; j++) {
|
---|
17 | if (b.charAt(i - 1) === a.charAt(j - 1)) {
|
---|
18 | matrix[i][j] = matrix[i - 1][j - 1];
|
---|
19 | }
|
---|
20 | else {
|
---|
21 | if (i > 1 &&
|
---|
22 | j > 1 &&
|
---|
23 | b.charAt(i - 2) === a.charAt(j - 1) &&
|
---|
24 | b.charAt(i - 1) === a.charAt(j - 2)) {
|
---|
25 | matrix[i][j] = matrix[i - 2][j - 2] + 1;
|
---|
26 | }
|
---|
27 | else {
|
---|
28 | matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
|
---|
29 | }
|
---|
30 | }
|
---|
31 | }
|
---|
32 | }
|
---|
33 | return matrix[b.length][a.length];
|
---|
34 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.