hamming('10101010','01010101')
Yukarıdaki sonucu olmalıdır 8.
Bunu uygulamak için nasıl?
Buraya yüklenen GMP herhangi aynı uzunlukta ikili dizeleri için kolay bir çözümdür
function HammingDistance($bin1, $bin2) {
$a1 = str_split($bin1);
$a2 = str_split($bin2);
$dh = 0;
for ($i = 0; $i < count($a1); $i++)
if($a1[$i] != $a2[$i]) $dh++;
return $dh;
}
echo HammingDistance('10101010','01010101'); //returns 8
You don't need to implement it because it already exists: http://php.net/manual/en/function.gmp-hamdist.php
(Eğer GMP desteği varsa)
Eğer GMP desteği yoksa hep böyle bir şey var. Sadece uzunluğu 32 bit kadar ikili dizeleri çalışır olumsuz.
function hamdist($x, $y){
for($dist = 0, $val = $x ^ $y; $val; ++$dist){
$val &= $val - 1;
}
return $dist;
}
function hamdist_str($x, $y){
return hamdist(bindec($x), bindec($y));
}
echo hamdist_str('10101010','01010101'); //8
Kolayca substr_count() and the code provided in this comment on the PHP manual yardımı ile hamming işlev kodu olabilir.
/* hamdist is equivilent to: */
echo gmp_popcount(gmp_xor($ham1, $ham2)) . "\n";