Hash Function: Add the ASCII values of all characters in the key string and return the reminder obtained when divided by the size of the table. Example: If key = "Bob", and size = 53, we get (66 + 111 + 98) % 53 => 275 % 53 => 10. Collision Resolution Method: Linear Probe. The assignment consists of the following classes/files: - main.cpp (incomplete) - Student.h (given) - HashNode.h (given) - HashTable.h (given) - HashTable.cpp (incomplete) Read and understand the given code then write two functions: - insert hash - search hash
72 lines
1.6 KiB
C++
72 lines
1.6 KiB
C++
// Implementation file for the Hash class
|
|
// Written By: Iurii Tatishchev
|
|
// Changed by: Iurii Tatishchev
|
|
|
|
#include <string>
|
|
#include <utility>
|
|
|
|
#include "HashTable.h"
|
|
|
|
using namespace std;
|
|
|
|
/*~*~*~*
|
|
A simple hash function
|
|
*~**/
|
|
int HashTable::_hash(string key) const {
|
|
int sum = 0;
|
|
for (char c : key)
|
|
sum += c;
|
|
return sum % hashSize;
|
|
};
|
|
|
|
/*~*~*~*
|
|
hash insert - linear probe
|
|
*~**/
|
|
bool HashTable::insert(const Student &itemIn) {
|
|
if (count == hashSize)
|
|
return false;
|
|
int pos = _hash(itemIn.getName());
|
|
int collisions = 0;
|
|
while (hashAry[pos].getOccupied()) {
|
|
++pos;
|
|
++collisions;
|
|
pos = pos % hashSize;
|
|
}
|
|
hashAry[pos].setItem(itemIn);
|
|
hashAry[pos].setOccupied(1);
|
|
hashAry[pos].setNoCollisions(collisions);
|
|
count++;
|
|
|
|
return true;
|
|
}
|
|
|
|
/*~*~*~*
|
|
hash delete - linear probe
|
|
*~**/
|
|
bool HashTable::remove(Student &itemOut) {
|
|
return false;
|
|
}
|
|
|
|
/*~*~*~*
|
|
hash search - linear probe
|
|
search for key
|
|
if found:
|
|
- copy data to itemOut
|
|
- copy number of collisions for this key to noCol
|
|
- returns true
|
|
if not found, returns false
|
|
*~**/
|
|
bool HashTable::search(Student &itemOut, int &noCol, string key) {
|
|
int pos = _hash(key);
|
|
for (int collisions = 0; collisions < count; collisions++) {
|
|
if (!hashAry[pos].getOccupied()) return false;
|
|
if (hashAry[pos].getItem().getName() == key) {
|
|
itemOut = hashAry[pos].getItem();
|
|
noCol = hashAry[pos].getNoCollisions();
|
|
return true;
|
|
}
|
|
pos = (pos + 1) % hashSize;
|
|
}
|
|
return false;
|
|
}
|