-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashSet.cpp
More file actions
89 lines (74 loc) · 1.75 KB
/
HashSet.cpp
File metadata and controls
89 lines (74 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "HashSet.h"
#include "IntegerHashes.h"
#include "StringHashes.h"
#include <string>
HashSet::HashSet(){
this->nitems = 0;
this->nslots = 1000;
intfn = new SquareRootHash(10, nslots);
strfn = new JenkinsHash();
slots = new std::string*[nslots];
for (int i = 0; i < nslots; i++){
slots[i] = NULL;
}
}
HashSet::~HashSet(){
for (int i = 0; i<nslots; i++){
delete slots[i];
}
delete [] slots;
delete intfn;
delete strfn;
}
void HashSet::insert(const std::string& value){
int key = strfn->hash(value);
int index = intfn->hash(key);
while(slots[index]!=NULL){
index = (index+1) % nslots;
}
slots[index]=new std::string(value);
nitems++;
if( ((double) nitems) / ((double) nslots) > 0.75){
this->rehash();
}
}
bool HashSet::lookup(const std::string& value) const{
int key = strfn->hash(value);
int index = intfn->hash(key);
while (slots[index] != NULL){
if(*(slots[index]) == value){
return true;
}
index = (index+1) % nslots;
}
return false;
}
void HashSet::rehash(){
// creating new array for slots
std::string** oldSlots = slots;
slots = new std::string*[nslots*2];
for(int i=0; i<nslots*2; i++){
slots[i] = NULL;
}
// redefine SquareRootHash
delete intfn;
this->intfn = new SquareRootHash(10, nslots*2);
// insert each element in slots into newSlots
for(int i=0; i<nslots; i++){
if(oldSlots[i] != NULL){
int key = strfn->hash(*(oldSlots[i]));
int index = intfn->hash(key);
while (slots[index] != NULL){
index=(index+1) % (nslots*2);
}
slots[index] = oldSlots[i];
}
}
// delete unneeded array
for(int i =0; i<nslots; i++){
delete oldSlots[i];
}
delete [] slots;
// update parameters
nslots *= 2;
}