#include "hashtable.h" #define DEBUG 1 Hashtable::Hashtable() { for(int i = 0; i < TABLE_SIZE; i++) table[i] = 0; } //Hash Function: sum of the ASCII codes of the characters % TABLE_SIZE int Hashtable::hash (char *l) { int sum = 0; int len = strlen(l); for(int i = 0; i < len; i++) sum += l[i]; return sum % TABLE_SIZE; } //produces new index in the array int Hashtable::rehash(int i) { i = (i+1)%TABLE_SIZE; return i; } bool Hashtable::insert (Type* new_item) { int index, new_index, counter = -1; index = hash(new_item->get_key()); if(DEBUG) cout << endl << "The index given by a hashfunction is " << index << endl; bool result = false; //if the spot is empty, or the record has been deleted, or the keys are the same if(table[index] == 0 || (strcmp(table[index]->get_key(), "*") == 0) || strcmp (new_item->get_key(), table[index]->get_key()) == 0) { table[index] = new_item; result = true; if(DEBUG) cout << endl << "The index of the available spot is " << index << endl; return result; } new_index = rehash(index); while(new_index != index){ if(table[new_index] == 0 || (strcmp(table[new_index]->get_key(), "*")==0)){ table[new_index] = new_item; result = true; if(DEBUG) cout << endl << "The index of the available spot is " << new_index << endl; return result; } else if(strcmp(table[new_index]->get_key(), new_item->get_key()) == 0){//if the keys are the same, update the record table[new_index] = new_item; result = true; if(DEBUG) cout << endl << "The index of the available spot is " << new_index << endl; return result; } new_index = rehash(new_index); } return result; } Type * Hashtable::get_data(int ind) { return table[ind]; } void Hashtable::view() { for(int i = 0; i < TABLE_SIZE; i++) { if(table[i] == 0 || (strcmp(table[i]->get_key(), "*") == 0)) //if the spot has never been used or a record has been deleted continue; cout << "\nIndex " << i << ": " << *table[i]; } } Type * Hashtable::find (char* key) { int index, new_index; Type *item; new_index = index = hash(key); item = table[index]; if(item != 0) { if(strcmp(item->get_key(), key) == 0) return item; } new_index = rehash(index); while(new_index != index){ if(table[new_index] != 0){ if(strcmp(table[new_index]->get_key(), key) == 0) return table[new_index]; } new_index = rehash(new_index); } return 0; } bool Hashtable::remove(char *key) { int index, new_index; Type *item; bool result = false; new_index = index = hash(key); item = table[index]; if(item != 0){ if(strcmp(item->get_key(), key) == 0) { item->set_key("*"); result = true; return result; } } new_index = rehash(index); while(new_index != index){ if(table[new_index] != 0){ if(strcmp(table[new_index]->get_key(), key) == 0){ table[new_index]->set_key("*"); result = true; return result; } } new_index = rehash(new_index); } return result; }