This repository was archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamic_Perfect_Hashing.cpp
More file actions
73 lines (73 loc) · 2.58 KB
/
Dynamic_Perfect_Hashing.cpp
File metadata and controls
73 lines (73 loc) · 2.58 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
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
class DynamicPerfectHashing {
private:
int universeSize;
std::vector<std::vector<int>> hashTable;
std::vector<std::vector<int>> keys;
void buildSecondLevelHashTable(int bucket) {
int m = static_cast<int>(keys[bucket].size());
int secondLevelSize = m * m;
while (true) {
hashTable[bucket].assign(secondLevelSize, -1);
bool success = true;
for (int i = 0; i < m; ++i) {
int h = hash(keys[bucket][i], secondLevelSize);
if (hashTable[bucket][h] == -1) {
hashTable[bucket][h] = keys[bucket][i];
} else {
success = false;
break;
}
}
if (success) {
break;
}
secondLevelSize *= 2;
}
}
int hash(int key, int tableSize) const {
return key % tableSize;
}
public:
DynamicPerfectHashing(int universeSize) : universeSize(universeSize) {
int initialSize = static_cast<int>(sqrt(universeSize));
hashTable.resize(initialSize);
keys.resize(initialSize);
}
void insert(int key) {
int bucket = key % hashTable.size();
if (std::find(keys[bucket].begin(), keys[bucket].end(), key) == keys[bucket].end()) {
keys[bucket].push_back(key);
if (keys[bucket].size() * keys[bucket].size() > hashTable.size()) {
buildSecondLevelHashTable(bucket);
}
}
}
void remove(int key) {
int bucket = key % hashTable.size();
auto it = std::find(keys[bucket].begin(), keys[bucket].end(), key);
if (it != keys[bucket].end()) {
keys[bucket].erase(it);
buildSecondLevelHashTable(bucket);
}
}
bool contains(int key) const {
int bucket = key % hashTable.size();
int h = hash(key, static_cast<int>(keys[bucket].size() * keys[bucket].size()));
return hashTable[bucket][h] == key;
}
};
int main() {
DynamicPerfectHashing dynamicPerfectHashing(100);
dynamicPerfectHashing.insert(42);
dynamicPerfectHashing.insert(13);
dynamicPerfectHashing.insert(88);
std::cout << "Contains 13? " << (dynamicPerfectHashing.contains(13) ? "Yes" : "No") << std::endl;
std::cout << "Contains 99? " << (dynamicPerfectHashing.contains(99) ? "Yes" : "No") << std::endl;
dynamicPerfectHashing.remove(13);
std::cout << "After removing 13, Contains 13? " << (dynamicPerfectHashing.contains(13) ? "Yes" : "No") << std::endl;
return 0;
}