#include #include #include // Two strings may either be equal or unequal. // This Boolean-valued question may be answered // by simply going through the two strings until // two characters are found that are unequal. // // We may instead ask the question: // // "How different are two strings?" // // One way of describing how different two strings // of equal length are is the Hamming distance. // // The Hamming distance between two strings of equal // length is the number of positions at which the // corresponding characters differ. // // For example, the Hamming distance between // // "Hay" // "Day" // // is 1. // // The Hamming distance is defined here only for // strings of equal length. Your function should // therefore assert that the two strings have the // same length. // Function declarations std::size_t hamming_distance( char const str1[], char const str2[] ); int main(); // Function definitions int main() { std::cout << hamming_distance( "Hi", "SI" ) << std::endl; std::cout << hamming_distance( "Hay", "Day" ) << std::endl; std::cout << hamming_distance( "These are equal", "These are equal" ) << std::endl; std::cout << hamming_distance( "These aren't equal", "These are unequal." ) << std::endl; return 0; } std::size_t hamming_distance( char const str1[], char const str2[] ) { // Enter your implementation here. return 0; } // You do not need to determine the lengths of the // two strings before calculating the Hamming distance. // // Continue while neither string has reached its null // character. For each pair of corresponding characters, // increase the distance if they are different. // // Once either string ends, what must be true if the // two strings have the same length? // Here is one solution: /* std::size_t hamming_distance( char const str1[], char const str2[] ) { std::size_t distance{ 0 }; std::size_t k{ 0 }; while ( (str1[k] != '\0') && (str2[k] != '\0') ) { if ( str1[k] != str2[k] ) { ++distance; } ++k; } // The Hamming distance is defined here only for // strings of equal length. Therefore, if either // string has ended, the other must end at the // same position. assert( (str1[k] == '\0') && (str2[k] == '\0') ); return distance; } */