forked from njones93531/4620Project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash_table.cpp
More file actions
97 lines (87 loc) · 2.24 KB
/
hash_table.cpp
File metadata and controls
97 lines (87 loc) · 2.24 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
90
91
92
93
94
95
96
97
#include <iostream>
#include <list>
#include <cstring>
#include <fstream>
using namespace std;
class HashTable {
private:
static const int hashGroups = 100;
// List 1, index 0, list 2, index 1, ...
list<pair<int, string> > table[hashGroups];
public:
bool isEmpty() const;
int hashFunction(int key);
void insertItem(int key, string value);
void removeItem(int key);
string searchTable(int key);
void printTable();
};
// Check for empty
bool HashTable::isEmpty() const {
int sum{};
for (int i{}; i < hashGroups; i++) {
sum += table[i].size();
}
if(!sum) {
return true;
}
return false;
}
// hash function
int HashTable::hashFunction(int key) {
// if key is 905, this return 5
return key % hashGroups;
}
// inserting item
void HashTable::insertItem(int key, string value) {
int hashValue = hashFunction(key);
auto& cell = table[hashValue];
auto bItr = begin(cell);
bool keyExists = false;
for (; bItr != end(cell); bItr++) {
if (bItr->first == key) {
keyExists = true;
bItr->second = value;
break;
}
}
if (!keyExists) {
cell.emplace_back(key, value);
}
return;
}
// removing item
void HashTable::removeItem(int key) {
int hashValue = hashFunction(key);
auto& cell = table[hashValue];
auto bItr = begin(cell);
bool keyExists = false;
for (; bItr != end(cell); bItr++) {
if (bItr->first == key) {
keyExists = true;
bItr = cell.erase(bItr);
break;
}
}
if (!keyExists) {
// Not Found;
}
return;
}
// printing hash table
void HashTable::printTable() {
ofstream myfile ("Tried_Passwords.txt");
for (int i{}; i < hashGroups; i++) {
if (table[i].size() == 0) continue;
auto bItr = table[i].begin();
for(; bItr != table[i].end(); bItr++) {
// cout << "Key: " << bItr->first << " Value: " << bItr->second << endl;
if (myfile.is_open()) {
// myfile << bItr->first << ": " << bItr->second << "\n";
myfile << bItr->second << "\n";
}
}
}
myfile.close();
return;
}