-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJaroWinkler.php
99 lines (67 loc) · 1.88 KB
/
JaroWinkler.php
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
93
94
95
96
97
98
99
<?php
// this is a brute porting of two Python functions by:
//
// 'mohit kumar 29' (https://auth.geeksforgeeks.org/user/mohit%20kumar%2029/) / Jaro
// 'AnkitRai01' (https://auth.geeksforgeeks.org/user/ankthon) / JaroWinkler
//
// ref. https://www.geeksforgeeks.org/jaro-and-jaro-winkler-similarity/
// warning: untested
function Jaro(string $s1, string $s2)
{
if ($s1 === $s2) {
return 1.0;
}
$len1 = strlen($s1);
$len2 = strlen($s2);
$max_dist = floor(max($len1, $len2) / 2) - 1;
$match = 0;
$hash_s1 = array_fill(0, $len1, 0);
$hash_s2 = array_fill(0, $len2, 0);
for ($i = 0; $i < $len1; $i++) {
for ($j = max(0, $i - $max_dist); $j < min($len2, $i + $max_dist + 1); $j++) {
if ($s1[$i] == $s2[$j] && $hash_s2[$j] == 0) {
$hash_s1[$i] = 1;
$hash_s2[$j] = 1;
$match += 1;
break;
}
}
}
if ($match == 0) {
return 0.0;
}
$t = $point = 0;
for ($i = 0; $i < $len1; $i++) {
if ($hash_s1[$i]) {
while ($hash_s2[$point] == 0) {
$point += 1;
}
if ($s1[$i] != $s2[$point]) {
$t += 1;
}
$point += 1;
}
}
$t = intval($t / 2);
return ($match / $len1 + $match / $len2 + ($match - $t) / $match) / 3.0;
}
//
function JaroWinkler(string $s1, string $s2)
{
$jaro_dist = Jaro($s1, $s2);
if ($jaro_dist > 0.7) {
$prefix = 0;
$m = min(strlen($s1), strlen($s2));
for ($i = 0; $i < $m; $i++) {
if ($s1[$i] == $s2[$i]) {
$prefix += 1;
} else {
break;
};
}
$prefix = min(4, $prefix);
$jaro_dist += 0.1 * $prefix * (1 - $jaro_dist);
}
return $jaro_dist;
}
echo JaroWinkler("trate", "trace");