-
Notifications
You must be signed in to change notification settings - Fork 0
/
HashTable.cpp
397 lines (332 loc) · 9.44 KB
/
HashTable.cpp
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
//============================================================================
// Name : HashTable.cpp
// Author : David France
// Version : 1.0
//============================================================================
#include <algorithm>
#include <climits>
#include <iostream>
#include <string> // atoi
#include <time.h>
#include "CSVparser.hpp"
using namespace std;
//============================================================================
// Global definitions visible to all methods and classes
//============================================================================
const unsigned int DEFAULT_SIZE = 179;
// forward declarations
double strToDouble(string str, char ch);
// define a structure to hold bid information
struct Bid {
string bidId; // unique identifier
string title;
string fund;
double amount;
Bid() {
amount = 0.0;
}
};
void displayBid(Bid bid);
//============================================================================
// Hash Table class definition
//============================================================================
/**
* Define a class containing data members and methods to
* implement a hash table with chaining.
*/
class HashTable {
private:
struct Node{
Bid bid;
unsigned key;
Node* next;
Node() {
key = UINT_MAX;
next = nullptr;
}
Node(Bid newBid) : Node() {
bid = newBid;
}
Node(Bid newBid, unsigned newKey) : Node() {
bid = newBid;
key = newKey;
}
};
vector<Node> nodes;
unsigned tableSize = DEFAULT_SIZE;
unsigned int hash(int key);
public:
HashTable();
HashTable(unsigned size);
virtual ~HashTable();
void Insert(Bid bid);
void PrintAll();
void Remove(string bidId);
Bid Search(string bidId);
};
/**
* Default constructor
*/
HashTable::HashTable() {
// Initialize the structures used to hold bids
nodes.resize(tableSize);
}
HashTable::HashTable(unsigned size) {
nodes.resize(size);
}
/**
* Destructor
*/
HashTable::~HashTable() {
// Free storage when class is destroyed
nodes.erase(nodes.begin());
}
/**
* Calculate the hash value of a given key.
* Note that key is specifically defined as
* unsigned int to prevent undefined results
* of a negative list index.
*
* @param key The key to hash
* @return The calculated hash
*/
unsigned int HashTable::hash(int key) {
// Calculate a hash value
return key % tableSize;
}
/**
* Insert a bid
*
* @param bid The bid to insert
*/
void HashTable::Insert(Bid bid) {
// Get hash value of bidId
unsigned key = hash(atoi(bid.bidId.c_str()));
// Get node pointer for first node at key
Node* oldNode = &(nodes.at(key));
// If no nodes exist, insert first node at key, else iterate to end of
// chain and insert node there
if (oldNode == nullptr) {
Node* newNode = new Node(bid, key);
nodes.insert(nodes.begin() + key, (*newNode));
} else {
if (oldNode->key == UINT_MAX) {
oldNode->key = key;
oldNode->bid = bid;
oldNode->next = nullptr;
} else {
while (oldNode->next != nullptr) {
oldNode = oldNode->next;
}
oldNode->next = new Node(bid, key);
}
}
}
/**
* Print all bids
*/
void HashTable::PrintAll() {
// Iterate through each index of nodes, printing all values at each index
for (unsigned i = 0; i < nodes.size(); ++i) {
// Get node pointer for first node at key
Node* node = &(nodes.at(i));
if (node == nullptr || node->key == UINT_MAX) {
continue;
}
cout << "Key ";
// While node pointer is not null, print bid information, then move to
// next node.
while(node != nullptr) {
cout << i << ": ";
displayBid(node->bid);
node = node->next;
}
}
}
/**
* Remove a bid
*
* @param bidId The bid id to search for
*/
void HashTable::Remove(string bidId) {
// Get hash value of bidId
unsigned key = hash(atoi(bidId.c_str()));
// Erase value at key from vector
nodes.erase(nodes.begin() + key);
}
/**
* Search for the specified bidId
*
* @param bidId The bid id to search for
*/
Bid HashTable::Search(string bidId) {
// Empty bid to return if none found
Bid bid;
// Get hash value of bidId
unsigned key = hash(atoi(bidId.c_str()));
// Get node pointer for first node at key
Node* node = &(nodes.at(key));
// If no node at key, return empty bid
if (node == nullptr || node->key == UINT_MAX) {
return bid;
}
// If first value at key is bid to be searched, return that bid
if (node->bid.bidId.compare(bidId) == 0) {
return node->bid;
}
// If more than one node exists at key, iterate through and return bid
// if bidId equals bidId to be searched.
while(node != nullptr) {
if (node->key != UINT_MAX && node->bid.bidId.compare(bidId) == 0) {
return node->bid;
}
node = node->next;
}
// If no bid has been returned, return empty bid.
return bid;
}
//============================================================================
// Static methods used for testing
//============================================================================
/**
* Display the bid information to the console (std::out)
*
* @param bid struct containing the bid info
*/
void displayBid(Bid bid) {
cout << bid.bidId << "| " << bid.title << " | " << bid.amount << " | "
<< bid.fund << endl;
return;
}
/**
* Load a CSV file containing bids into a container
*
* @param csvPath the path to the CSV file to load
* @return a container holding all the bids read
*/
void loadBids(string csvPath, HashTable* hashTable) {
cout << "Loading CSV file " << csvPath << endl;
// initialize the CSV Parser using the given path
csv::Parser file = csv::Parser(csvPath);
// read and display header row - optional
vector<string> header = file.getHeader();
for (auto const& c : header) {
cout << c << " | ";
}
cout << "" << endl;
int count = 0;
try {
// loop to read rows of a CSV file
for (unsigned int i = 0; i < file.rowCount(); i++) {
// Create a data structure and add to the collection of bids
Bid bid;
bid.bidId = file[i][1];
bid.title = file[i][0];
bid.fund = file[i][8];
bid.amount = strToDouble(file[i][4], '$');
//cout << "Item: " << bid.title << ", Fund: " << bid.fund << ", Amount: " << bid.amount << endl;
// push this bid to the end
hashTable->Insert(bid);
count++;
}
} catch (csv::Error &e) {
std::cerr << e.what() << std::endl;
}
cout << count << " bids read" << endl;
}
/**
* Simple C function to convert a string to a double
* after stripping out unwanted char
*
* credit: http://stackoverflow.com/a/24875936
*
* @param ch The character to strip out
*/
double strToDouble(string str, char ch) {
str.erase(remove(str.begin(), str.end(), ch), str.end());
return atof(str.c_str());
}
/**
* The one and only main() method
*/
int main(int argc, char* argv[]) {
// process command line arguments
string csvPath, bidKey;
switch (argc) {
case 2:
csvPath = argv[1];
bidKey = "98109";
break;
case 3:
csvPath = argv[1];
bidKey = argv[2];
break;
default:
csvPath = "eBid_Monthly_Sales.csv";
bidKey = "98109";
}
// Define a timer variable
clock_t ticks;
// Define a hash table to hold all the bids
HashTable* bidTable;
Bid bid;
// Boolean to display error if bids never loaded
bool bidsLoaded = false;
int choice = 0;
while (choice != 9) {
cout << "Menu:" << endl;
cout << " 1. Load Bids" << endl;
cout << " 2. Display All Bids" << endl;
cout << " 3. Find Bid" << endl;
cout << " 4. Remove Bid" << endl;
cout << " 9. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
bidTable = new HashTable();
// Initialize a timer variable before loading bids
ticks = clock();
// Complete the method call to load the bids
loadBids(csvPath, bidTable);
bidsLoaded =true;
// Calculate elapsed time and display result
ticks = clock() - ticks; // current clock ticks minus starting clock ticks
cout << "time: " << ticks << " clock ticks" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;
break;
case 2:
if (!bidsLoaded) {
cout << "No bids have been loaded" << endl;
break;
}
bidTable->PrintAll();
break;
case 3:
if (!bidsLoaded) {
cout << "No bids have been loaded" << endl;
break;
}
ticks = clock();
bid = bidTable->Search(bidKey);
ticks = clock() - ticks; // current clock ticks minus starting clock ticks
if (!bid.bidId.empty()) {
displayBid(bid);
} else {
cout << "Bid Id " << bidKey << " not found." << endl;
}
cout << "time: " << ticks << " clock ticks" << endl;
cout << "time: " << ticks * 1.0 / CLOCKS_PER_SEC << " seconds" << endl;
break;
case 4:
if (!bidsLoaded) {
cout << "No bids have been loaded" << endl;
break;
}
bidTable->Remove(bidKey);
break;
}
}
cout << "Good bye." << endl;
return 0;
}