-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathjarowinkler.c
92 lines (77 loc) · 2.3 KB
/
jarowinkler.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* c: jarowinkler.c
* Copyright (C) 2011 Miguel Serrano
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#define SCALING_FACTOR 0.1
static int max(int x, int y) {
return x > y ? x : y;
}
static int min(int x, int y) {
return x < y ? x : y;
}
double jaro_winkler_distance(const char *s, const char *a) {
int i, j, l;
int m = 0, t = 0;
int sl = strlen(s);
int al = strlen(a);
int sflags[sl], aflags[al];
int range = max(0, max(sl, al) / 2 - 1);
double dw;
if (!sl || !al)
return 0.0;
for (i = 0; i < al; i++)
aflags[i] = 0;
for (i = 0; i < sl; i++)
sflags[i] = 0;
/* calculate matching characters */
for (i = 0; i < al; i++) {
for (j = max(i - range, 0), l = min(i + range + 1, sl); j < l; j++) {
if (a[i] == s[j] && !sflags[j]) {
sflags[j] = 1;
aflags[i] = 1;
m++;
break;
}
}
}
if (!m)
return 0.0;
/* calculate character transpositions */
l = 0;
for (i = 0; i < al; i++) {
if (aflags[i] == 1) {
for (j = l; j < sl; j++) {
if (sflags[j] == 1) {
l = j + 1;
break;
}
}
if (a[i] != s[j])
t++;
}
}
t /= 2;
/* Jaro distance */
dw = (((double)m / sl) + ((double)m / al) + ((double)(m - t) / m)) / 3.0;
/* calculate common string prefix up to 4 chars */
l = 0;
for (i = 0; i < min(min(sl, al), 4); i++)
if (s[i] == a[i])
l++;
/* Jaro-Winkler distance */
dw = dw + (l * SCALING_FACTOR * (1 - dw));
return dw;
}