-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash_table_search.cpp
More file actions
317 lines (262 loc) · 9.99 KB
/
Copy pathhash_table_search.cpp
File metadata and controls
317 lines (262 loc) · 9.99 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// # *********************************************************
// Program: hash_table_search_step.cpp
// Course: CCP6214 Algorithm Design and Analysis
// Lecture Class: TC2L
// Tutorial Class: TT5L
// Trimester: 2610
// Member_1: HEW WEE BO | hew.wee.bo@student.mmu.edu.my | 0128803121
// Member_2: ID | JEVAANRAJ A/L RAJA KUMARAN | jevaanraj.raja.kumaran@student.mmu.edu.my | 0179651973
// Member_3: ID | SHANJIF CAKRAVRTHI A/L KUPPAN @ SIVA KUMAR | shanjif.cakravthi@student.mmu.edu.my | 0195601010
// Member_4: ID | TEH ZHAO JIN | teh.zhao.jin@student.mmu.edu.my | 01111279290
// # *********************************************************
// Task Distribution
// Member_1: Hew Wee Bo
// Member_2: Jevaanraj
// Member_3: Shanjif
// Member_4: Teh Zhao Jin
// # *********************************************************
/* Purpose
Measure the running time of hash table search for:
- Best Case
- Average Case
- Worst Case */
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <chrono>
#include <climits>
using namespace std;
using namespace chrono;
struct Record {
long long key;
string value;
};
struct Node {
Record data;
Node* next;
};
class HashTable {
private:
int tableSize;
int numElements;
vector<Node*> table;
public:
HashTable(int size)
:tableSize(size), numElements(0), table(size, nullptr) {}
~HashTable(){
for (int i=0; i < tableSize; i++) {
Node* curr= table[i];
while (curr != nullptr) {
Node* temp = curr;
curr= curr->next;
delete temp;
}
}
}
int hashFunction(long long key) const{
return (int)((unsigned long long)key % (unsigned long long)tableSize);
}
void insert(const Record& rec) {
int idx = hashFunction(rec.key);
Node* newNode = new Node();
newNode->data = rec;
newNode->next = table[idx];
table[idx] = newNode;
numElements++;
}
Node* search(long long targetKey) const {
int idx = hashFunction(targetKey);
Node* curr = table[idx];
while (curr != nullptr) {
if (curr->data.key == targetKey) {
return curr;
}
curr = curr->next;
}
return nullptr;
}
long long getBestCaseKey() const {
for (int i = 0; i < tableSize; ++i) {
if (table[i] != nullptr) {
return table[i]->data.key;
}
}
return LLONG_MIN;
}
long long getLongestChainKey() const{
int maxLen=0;
long long worstKey = LLONG_MIN;
for (int i = 0; i < tableSize; i++){
if (table[i] == nullptr) continue;
int len = 0;
Node* curr = table[i];
Node* last = nullptr;
while (curr != nullptr) {
len++;
last = curr;
curr = curr->next;
}
if (len > maxLen) {
maxLen = len;
worstKey = last->data.key;
}
}
return worstKey;
}
vector<long long> getAllKeys() const {
vector<long long> keys;
for (int i = 0; i < tableSize; ++i) {
Node* curr = table[i];
while (curr != nullptr) {
keys.push_back(curr->data.key);
curr = curr->next;
}
}
return keys;
}
int getNumElements() const {
return numElements;
}
int getTableSize() const {
return tableSize;
}
};
vector<Record> parseCSV(const string& filename) {
vector<Record> records;
ifstream inFile(filename);
if (!inFile.is_open()) {
cerr << "Error opening file: " << filename << endl;
return records;
}
string line;
while (getline(inFile, line)) {
if (line.empty()) continue;
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
stringstream ss(line);
string keyStr, valueStr;
if (getline(ss, keyStr, ',') && getline(ss, valueStr)) {
try {
Record rec;
rec.key = stoll(keyStr);
rec.value = valueStr;
records.push_back(rec);
}catch (...){
cerr << "Error parsing line: " << line << endl;
}
}
}
inFile.close();
return records;
}
string extractDatasetSize(const string& filename) {
size_t underPos = filename.rfind('_');
size_t dotPos = filename.rfind('.');
if (underPos != string::npos && dotPos != string::npos && underPos < dotPos) {
return filename.substr(underPos + 1, dotPos - underPos - 1);
}
return "unknown";
}
int choosePrimeTableSize (int minSize) {
if (minSize < 2) return 2;
int candidate = (minSize % 2 == 0) ? minSize + 1 : minSize;
while (true) {
bool isPrime = true;
for (int i=2; (long long)i * i <= candidate; i++) {
if (candidate % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) return candidate;
candidate += 2;
}
return -1;
}
int main() {
// Comment/uncomment lines to choose which datasets to run.
// Multiple uncommented lines will run one after another.
vector<string> inputs = {
"dataset_1000.csv",
// "dataset_10000.csv",
//"dataset_100000.csv",
};
for (const string& datasetFile : inputs) {
string datasetSizeStr = extractDatasetSize(datasetFile);
cout << "Reading dataset from: " << datasetFile << endl;
vector<Record> records = parseCSV(datasetFile);
if (records.empty()) {
cerr << "No valid records found in the dataset." << endl;
return 1;
}
int n = (int)records.size();
// cout << "Loaded " << n << " records." << endl;
int tableSize = choosePrimeTableSize(n * 2);
// cout << "Building hash table with " << tableSize << " buckets..." << endl;
HashTable ht(tableSize);
for (const Record& rec : records) {
ht.insert(rec);
}
// cout << "Hash table built with " << ht.getNumElements() << " elements." << endl;
long long bestCaseKey = ht.getBestCaseKey();
long long worstCaseKey = ht.getLongestChainKey();
vector<long long> allKeys = ht.getAllKeys();
// cout << "Best case key: " << bestCaseKey << endl;
//cout << "Worst case key: " << worstCaseKey << endl;
// cout << "Average case key: " << allKeys[allKeys.size() / 2] << endl;
// cout << "TIming best case (" << n << " searches)..." << endl;
auto bcStart = high_resolution_clock::now();
volatile int bestFound = 0;
for (int i = 0; i < n; i++) {
Node* result = ht.search(bestCaseKey);
if (result != nullptr) bestFound++;
}
auto bcEnd = high_resolution_clock::now();
duration<double, std::milli> bestTime = duration_cast<duration<double, std::milli>>(bcEnd - bcStart);
// cout << "Timing average case (" << n << " searches)..." << endl;
auto acStart = high_resolution_clock::now();
volatile int avgFound = 0;
for (int i = 0; i < n; i++) {
Node* result = ht.search(allKeys[i]);
if (result != nullptr) avgFound++;
}
auto acEnd = high_resolution_clock::now();
duration<double, std::milli> avgTime = duration_cast<duration<double, std::milli>>(acEnd - acStart);
// cout << "Timing worst case (" << n << " searches)..." << endl;
auto wcStart = high_resolution_clock::now();
volatile int worstFound = 0;
for (int i = 0; i < n; i++) {
Node* result = ht.search(worstCaseKey);
if (result != nullptr) worstFound++;
}
auto wcEnd = high_resolution_clock::now();
duration<double, std::milli> worstTime = duration_cast<duration<double, std::milli>>(wcEnd - wcStart);
string outFilename = "hash_table_search_dataset_" + datasetSizeStr + ".txt";
ofstream outFile(outFilename);
if (!outFile.is_open()) {
cerr << "ERROR: Cannot create output file: " << outFilename << "\n";
return 1;
}
outFile << "\nResults for dataset size " << datasetSizeStr << ":\n";
outFile << "Best case: " << bestFound << "/" << n << " found\n Time = " << bestTime.count() << " milliseconds\n";
outFile << endl;
outFile << "Average case: " << avgFound << "/" << n << " found\n Time = " << avgTime.count() << " milliseconds\n";
outFile << endl;
outFile << "Worst case: " << worstFound << "/" << n << " found\n Time = " << worstTime.count() << " milliseconds\n";
outFile << endl;
outFile << "=======================================================\n";
outFile << endl;
outFile << "Results for dataset size n = " << n << "\n";
outFile << "Best case time: " << bestTime.count() << " milliseconds\n";
outFile << "Average case time: " << avgTime.count() << " milliseconds\n";
outFile << "Worst case time: " << worstTime.count() << " milliseconds\n";
outFile << endl;
outFile << "Output written to: " << outFilename << "\n";
outFile.close();
cout << "Results written to file: " << outFilename << "\n";
return 0;
}
}