PHP 8.5.0 RC4 available for testing

Voting

: min(nine, eight)?
(Example: nine)

The Note You're Voting On

vasyl at vasyltech dot com
9 years ago
Recursive algorithm usually is very elegant one. I found a way to get better precision without the recursion. Imagine two different (or same) length ribbons with letters on each. You simply shifting one ribbon to left till it matches the letter the first.

<?php

function similarity($str1, $str2) {
$len1 = strlen($str1);
$len2 = strlen($str2);

$max = max($len1, $len2);
$similarity = $i = $j = 0;

while ((
$i < $len1) && isset($str2[$j])) {
if (
$str1[$i] == $str2[$j]) {
$similarity++;
$i++;
$j++;
} elseif (
$len1 < $len2) {
$len1++;
$j++;
} elseif (
$len1 > $len2) {
$i++;
$len1--;
} else {
$i++;
$j++;
}
}

return
round($similarity / $max, 2);
}

$str1 = '12345678901234567890';
$str2 = '12345678991234567890';

echo
'Similarity: ' . (similarity($str1, $str2) * 100) . '%';
?>

<< Back to user notes page

To Top