hamming distance Algorithm

The Hamming distance algorithm is a widely-used method for measuring the similarity between two strings or sequences of equal length, typically in the context of error detection or correction, data compression, and cryptography. It was introduced by Richard Hamming, an American mathematician and computer scientist, in 1950 as part of his work on error-detecting and error-correcting codes. The algorithm calculates the number of positions at which the corresponding symbols in the two strings are different, providing a simple yet effective way to quantify the dissimilarity between them. In practical applications, the Hamming distance can be used to detect errors in data transmission or storage, as well as to correct those errors if the distance is not too large. For instance, in error-correcting codes such as Hamming codes, the Hamming distance allows the system to identify and correct single-bit errors and detect double-bit errors in a block of data. Moreover, in the field of bioinformatics, the Hamming distance algorithm can be used to compare DNA sequences and detect genetic mutations. In general, the Hamming distance offers a fast and efficient way to compare strings and sequences, making it a valuable tool in various domains of computer science and information theory.
/**
 The Hamming distance between two integers is the number of positions at which
 the corresponding bits are different.
 Given two integers x and y, calculate the Hamming distance.

 Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different
*/

#include <iostream>

int hamming_distance(int x, int y)
{
    // XOR will set only those bits in z which are different in x and y
    int z = x ^ y;

    // Now just count set bits in z.
    int count = 0;
    while (z)
    {
        count += (z % 2);
        z >>= 2;
    }
    return count;
}


int main()
{
    int x = 4;
    int y = 1;
    std::cout << "Hamming distance between " << x << " and " << y << " is : "
        <<  hamming_distance(x, y) << std::endl;
}

LANGUAGE:

DARK MODE: