MCPcopy Create free account
hub / github.com/git/git / levenshtein

Function levenshtein

levenshtein.c:41–86  ·  view source on GitHub ↗

* This function implements the Damerau-Levenshtein algorithm to * calculate a distance between strings. * * Basically, it says how many letters need to be swapped, substituted, * deleted from, or added to string1, at least, to get string2. * * The idea is to build a distance matrix for the substrings of both * strings. To avoid a large space complexity, only the last three rows * are kept

Source from the content-addressed store, hash-verified

39 * Note that this algorithm calculates a distance _iff_ d == a.
40 */
41int levenshtein(const char *string1, const char *string2,
42 int w, int s, int a, int d)
43{
44 int len1 = strlen(string1), len2 = strlen(string2);
45 int *row0, *row1, *row2;
46 int i, j;
47
48 ALLOC_ARRAY(row0, len2 + 1);
49 ALLOC_ARRAY(row1, len2 + 1);
50 ALLOC_ARRAY(row2, len2 + 1);
51
52 for (j = 0; j <= len2; j++)
53 row1[j] = j * a;
54 for (i = 0; i < len1; i++) {
55 int *dummy;
56
57 row2[0] = (i + 1) * d;
58 for (j = 0; j < len2; j++) {
59 /* substitution */
60 row2[j + 1] = row1[j] + s * (string1[i] != string2[j]);
61 /* swap */
62 if (i > 0 && j > 0 && string1[i - 1] == string2[j] &&
63 string1[i] == string2[j - 1] &&
64 row2[j + 1] > row0[j - 1] + w)
65 row2[j + 1] = row0[j - 1] + w;
66 /* deletion */
67 if (row2[j + 1] > row1[j + 1] + d)
68 row2[j + 1] = row1[j + 1] + d;
69 /* insertion */
70 if (row2[j + 1] > row2[j] + a)
71 row2[j + 1] = row2[j] + a;
72 }
73
74 dummy = row0;
75 row0 = row1;
76 row1 = row2;
77 row2 = dummy;
78 }
79
80 i = row1[len2];
81 free(row0);
82 free(row1);
83 free(row2);
84
85 return i;
86}

Callers 1

help_unknown_cmdFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected