Coding Practice

Write a program to find Hamming Distance

Hamming Distance

Hamming distance is a metric for comparing two binary data strings. While comparing two binary strings of equal length, Hamming distance is the number of bit positions in which the two bits are different.

Example: Find the distance between the vectors 01101010 and 11011011.
(01101010
11011011)
They differ in four places, So the Hamming distance d(01101010, 11011011) = 4.

Sample Output
Enter Comp1 data: 111101010
Enter Comp2 data: 010101010

Hamming Distance: 2
C-Source Code
#include<stdio.h>

void main()
{
    int i, comp1Len, comp2Len, hammingDistance = 0;
    char comp1[500], comp2[500];
input:
    printf("Enter Comp1 data: ");
    scanf("%s", comp1);
    printf("Enter Comp2 data: ");
    scanf("%s", comp2);

    for(i = 0; comp1[i] != '\0'; i++);
    comp1Len = i;

    for(i = 0; comp2[i] != '\0'; i++);
    comp2Len = i;

    if(comp1Len != comp2Len)
    {
        printf("\nComp1 and Comp2 length are not same!\n\n");
        goto input;
    }

    for(i = 0; i < comp1Len; i++)
    {
        if(comp1[i] != comp2[i])
        {
            hammingDistance++;
        }
    }
    printf("\nHamming Distance: %d\n\n", hammingDistance);
}
Sample Output
Enter Comp1 data: 01101010
Enter Comp2 data: 11011011

Hamming Distance: 4

No comments:

Post a Comment

Change Theme
X