#include #include using namespace std; const int hashsize = 60000; unsigned int hash(string s) { unsigned int h = 278364; int len = s.length(); for (int i = 0; i < len; i += 1) h = h * 69 + s[i]; return h % hashsize; } int search(int * htable, ifstream & fd, string name) { int hashpos = hash(name); int origpos = hashpos; int cost = 0; bool ok = false; while (true) { int ptr = htable[hashpos]; if (ptr == -1) { if (! ok) cout << "'" << name << "' not found\n"; return cost; } fd.seekg(ptr, ios::beg); string line; getline(fd, line); if (fd.fail()) { cerr << "bad hash position\n"; return cost; } cost += 1; string state = line.substr(0, 2); line = line.substr(3); if (line == name) { cout << "found " << line << " (" << state << ")\n"; ok = true; } hashpos += 1; if (hashpos >= hashsize) hashpos = 0; if (hashpos == origpos) { if (! ok) cerr << "Hash table full\n"; return cost; } } } int main() { ifstream fd("/home/www/class/een318/namesonly.txt", ios::in); if (fd.fail()) { cerr << "didn't work\n"; exit(1); } ifstream fi("index.dat", ios::in | ios::binary); if (fi.fail()) { cerr << "creating file didn't work\n"; exit(1); } int * h = new int[hashsize]; fi.read((char *)h, hashsize * sizeof(int)); int n = fi.gcount(); if (n != hashsize * sizeof(int)) { cerr << "error reading\n"; exit(1); } int filepos = 0; while (true) { string line; cout << "? "; getline(cin, line); if (cin.fail()) break; int cost = search(h, fd, line); cout << "cost = " << cost << "\n"; } fd.close(); fi.close(); }