Current Location: Home> Latest Articles> PHP Implementation of Hamming Distance Total Calculation Example

PHP Implementation of Hamming Distance Total Calculation Example

gitbox 2025-06-30

What is Hamming Distance?

Hamming distance is a method used to measure the difference between two strings of equal length. It is defined as the number of different characters in corresponding positions of the two strings.

For example, consider the following two strings:

"abcdefgh" and "abcxtdhy"

The Hamming distance between them is 4 because the characters at positions 4, 5, 6, and 8 differ.

PHP Example: Calculating Total Hamming Distance

Suppose we have an array of multiple binary strings of equal length, like this:


// An array of multiple equal-length binary strings
$array = ["1100", "1010", "1111", "0000"];

The question is: how can we calculate the total Hamming distance between all pairs of strings in this array? We can first define a function to calculate the Hamming distance:


/**
 * Calculate Hamming Distance
 * @param string $str1
 * @param string $str2
 * @return int
 */
function hammingDistance($str1, $str2) {
    $dist = 0;
    $n = strlen($str1);
    for ($i = 0; $i < $n; $i++) {
        if ($str1[$i] !== $str2[$i]) {
            $dist++;
        }
    }
    return $dist;
}

This function simply iterates through both strings and increments the counter by 1 whenever the characters at corresponding positions differ.

Next, we can use two nested loops to calculate the total Hamming distance for all pairs of strings:


$len = count($array);
$sum = 0;
for ($i = 0; $i < $len; $i++) {
    for ($j = $i + 1; $j < $len; $j++) {
        $sum += hammingDistance($array[$i], $array[$j]);
    }
}
echo $sum; // Output: 10

This way, we can obtain the total Hamming distance for all binary strings in the array.

Example Explanation

For the array ["1100", "1010", "1111", "0000"], the Hamming distance between each pair of binary strings is as follows:

1100
1010   2
1111 3 1
0000 4 2 5

Thus, the total Hamming distance is 10.

Conclusion

This article introduced the basic concept of Hamming distance and provided a PHP example demonstrating how to calculate the total Hamming distance for an array of binary strings. Hamming distance has wide applications in fields like data transmission, encryption, and error correction, and understanding this method is useful when solving related problems.