1 #include "levenshtein.h"
7 * This function implements the Damerau-Levenshtein algorithm to
8 * calculate a distance between strings.
10 * Basically, it says how many letters need to be swapped, substituted,
11 * deleted from, or added to string1, at least, to get string2.
13 * The idea is to build a distance matrix for the substrings of both
14 * strings. To avoid a large space complexity, only the last three rows
15 * are kept in memory (if swaps had the same or higher cost as one deletion
16 * plus one insertion, only two rows would be needed).
18 * At any stage, "i + 1" denotes the length of the current substring of
19 * string1 that the distance is calculated for.
21 * row2 holds the current row, row1 the previous row (i.e. for the substring
22 * of string1 of length "i"), and row0 the row before that.
24 * In other words, at the start of the big loop, row2[j + 1] contains the
25 * Damerau-Levenshtein distance between the substring of string1 of length
26 * "i" and the substring of string2 of length "j + 1".
28 * All the big loop does is determine the partial minimum-cost paths.
30 * It does so by calculating the costs of the path ending in characters
31 * i (in string1) and j (in string2), respectively, given that the last
32 * operation is a substition, a swap, a deletion, or an insertion.
34 * This implementation allows the costs to be weighted:
37 * - s (as in "Substitution")
38 * - a (for insertion, AKA "Add")
39 * - d (as in "Deletion")
41 * Note that this algorithm calculates a distance _iff_ d == a.
43 int levenshtein(const char *string1, const char *string2,
44 int w, int s, int a, int d)
46 int len1 = strlen(string1), len2 = strlen(string2);
47 int *row0 = malloc(sizeof(int) * (len2 + 1));
48 int *row1 = malloc(sizeof(int) * (len2 + 1));
49 int *row2 = malloc(sizeof(int) * (len2 + 1));
52 for (j = 0; j <= len2; j++)
54 for (i = 0; i < len1; i++) {
57 row2[0] = (i + 1) * d;
58 for (j = 0; j < len2; j++) {
60 row2[j + 1] = row1[j] + s * (string1[i] != string2[j]);
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;
67 if (row2[j + 1] > row1[j + 1] + d)
68 row2[j + 1] = row1[j + 1] + d;
70 if (row2[j + 1] > row2[j] + a)
71 row2[j + 1] = row2[j] + a;