-
-
Notifications
You must be signed in to change notification settings - Fork 462
/
Distance.php
57 lines (46 loc) · 1.42 KB
/
Distance.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
<?php
/**
* Find distance (Levenshtein distance)
*
* Compute the difference between two sequences, ie, the minimum number of changes
* to get to $str2 from $str1
*
* @param string $str1
* @param string $str2
* @return int the minimum number of changes to transform one string into another
*/
function findDistance($str1, $str2)
{
$lenStr1 = strlen($str1);
$lenStr2 = strlen($str2);
if ($lenStr1 == 0) {
return $lenStr2;
}
if ($lenStr2 == 0) {
return $lenStr1;
}
$distanceVectorInit = [];
$distanceVectorFinal = [];
for ($i = 0; $i < $lenStr1 + 1; $i++) {
$distanceVectorInit[] = 0;
$distanceVectorFinal[] = 0;
}
for ($i = 0; $i < $lenStr1 + 1; $i++) {
$distanceVectorInit[$i] = $i;
}
for ($i = 0; $i < $lenStr2; $i++) {
$distanceVectorFinal[0] = $i + 1;
// use formula to fill in the rest of the row
for ($j = 0; $j < $lenStr1; $j++) {
$substitutionCost = 0;
if ($str1[$j] == $str2[$i]) {
$substitutionCost = $distanceVectorInit[$j];
} else {
$substitutionCost = $distanceVectorInit[$j] + 1;
}
$distanceVectorFinal[$j + 1] = min($distanceVectorInit[$j + 1] + 1, min($distanceVectorFinal[$j] + 1, $substitutionCost));
}
$distanceVectorInit = $distanceVectorFinal;
}
return $distanceVectorFinal[$lenStr1];
}