Search code examples
c++arraysfunctioncharhamming-distance

Hamming Distance: Incorrect Count


I'm trying to create a function to calculate the Hamming Distance between two strings. When I call this function, it should tell me the number of characters that do not match between the two strings.

My output is not correct. I keep getting random number results. Below is my code:

using namespace std;

// function to calculate Hamming distance
int HammingDistance(char seq1[], char seq2[])
{
    int i = 0, count = 0;
    while (seq1[i] != ' ')
    {
        if (seq1[i] != seq2[i])
            count++;
        i++;
    }
    return count;
}


int main()
{
    char seq1[] = "doga";
    char seq2[] = "dogb";

    cout << HammingDistance(seq1, seq2) << endl;        

    return 0;
}

I keep getting random number results in my output, like 99 or 207.

When in this example, I should get 1.

Any help on where I'm going wrong is greatly appreciated! Thank you.


Solution

  • The condition seq1[i] != ' ' is not a good way of checking whether you have reached the end of the string. Assuming that your strings are null terminated then you could use seq1[i] != '\0' instead.

    The reason that you are seeing "random" results is that the loop is not encountering a space within the string and is continuing to read past the end of the strings into other parts of the program's memory. The loop only stops when it encounters a byte of memory that happens to contain the same bits as the representation of ' '.

    You should also think about how to handle cases where the two strings are different lengths.