// // Hash code tests and analytics. // // g++ -std=c++20 -o hashing hashing.cpp #include // cout, endl using std::cout; using std::endl; #include // ifstream using std::ifstream; #include // string, getline using std::string; using std::getline; #include // vector using std::vector; // // Global structures, constants, and variables // const string FILE_NAME = "magicitems.txt"; const int LINES_IN_FILE = 666; const int HASH_TABLE_SIZE = 250; void readFileIntoVector(vector& victor) { string line = ""; ifstream fileStream(FILE_NAME); // Implicitly opens the file too. It's a C++ thing, I guess. while( getline(fileStream, line) ) { victor.push_back(line); } fileStream.close(); } int makeHashCode(string item) { // Transform item to UPPER CASE. transform(item.begin(), item.end(), item.begin(),::toupper); // Iterate over all letters in the item string, totalling their ASCII values. int letterTotal = 0; for (int i = 0; i < item.length(); i++) { letterTotal = letterTotal + (int)item[i]; } // Scale letterTotal to fit in HASH_TABLE_SIZE. int hashCode = letterTotal % HASH_TABLE_SIZE; // % is the "mod" operator // TODO: Experiment with letterTotal * 2, 3, 5, 50, etc. return hashCode; } // // Main entry point for this program. // int main(int argc, char* argv[]) { int retCode = 0; cout << "----------------------------" << endl; cout << "Hash code tests and analysis" << endl; cout << "----------------------------" << endl; cout << "Hash table size = " << HASH_TABLE_SIZE << endl; cout << "Reading " << LINES_IN_FILE << " lines from file [" << FILE_NAME << "] . . ." << endl; vector magicItems; readFileIntoVector(magicItems); // Print the items in the vector and each of their hash code values. for (int i = 0; i < magicItems.size(); i++) { cout << "Item " << i << ": " << magicItems[i] << " = " << makeHashCode(magicItems[i]) << endl; } return retCode; }