#include #include #include // A hash function is a function that takes an object // (in this case, a string) and returns an integer. // // In this exercise, our hash function will return a // 32-bit unsigned integer. // // Each time the hash function is called on the same // string, it should return the same value. Also, two // strings containing the same characters in the same // order must have the same hash value. // // Hash functions have many uses, but for now we will // start with a very simple one. // // A character is stored in one byte and can therefore // be interpreted as a small unsigned integer. Thus, // adding characters to an integer adds their numerical // values. // // For example: // // std::uint32_t value{ 0 }; // value += 'F'; // value += 'P'; // // For ASCII characters, // // 'F' has the value 70 // 'P' has the value 80 // // so value will contain 150. // // Implement a function that returns a hash value for // a string by adding the numerical values of all the // characters in the string. // Function declarations std::uint32_t hash( char const *str ); int main(); // Function definitions int main() { std::uint32_t value{ 0 }; value += 'F'; value += 'P'; std::cout << value << std::endl; // This should have a hash value of 2682. char const *str1{ "Fundamentals of Programming" }; std::cout << hash( str1 ) << std::endl; // This should have a hash value of 2707. char const *str2{ "In a hole there lived a Hobbit." }; std::cout << hash( str2 ) << std::endl; // This should have a hash value of 101. // This is the ASCII value of 'e'. char const *str3{ "e" }; std::cout << hash( str3 ) << std::endl; // This should have a hash value of 0. char const *str4{ "" }; std::cout << hash( str4 ) << std::endl; return 0; } std::uint32_t hash( char const *str ) { // Enter your implementation here. return 0; } // Remember that a C-style string ends with the null // character '\0'. // // Thus, continue adding characters until you reach // the null character. The null character itself is // not part of the string and does not need to be // included in the sum. // Here is one solution: /* std::uint32_t hash( char const *str ) { std::uint32_t value{ 0 }; // Keep going through the string until we reach // the null character '\0'. for ( std::size_t k{ 0 }; str[k] != '\0'; ++k ) { value += static_cast( str[k] ); } return value; } */