-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.h
533 lines (439 loc) · 13.4 KB
/
Trie.h
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
/* File: Trie.h
* Name: Paulo, Matt
* Date: 4/15/2017
* Team: Sandwich
*/
/* This Trie will be used to store the username and name
* of all users. It will be used particularly for the following:
*
* 1. Autocompletion of a string. For example, if you want to
* search for a different user's account, you can search for
* either the name or username of the account and you will
* get a correct result.
*
* 2. Retrieving a particular user by either username or name.
* Users must have unique usernames, however they all can
* have the same name. Doing a "get" for either string will
* return a vector of all the possible users that belong to
* that string.
*
* 3. Validating that a user exists.
*
*
* BEHAVIOR:
*
* Every function that takes a string argument first validates
* if the string given is ONLY spaces and alpha characters.
* All string are saved as lowercase, and all searches first
* convert the given string to lowercase. Keep in mind
* that usernames may appear with casing, but this makes the
* searches non-case-sensitive.
*
*
* INSTANTIATION OF TRIE:
* sandwich::Trie<Type> trie;
*/
#ifndef SANDWICH_TRIE_H_
#define SANDWICH_TRIE_H_
#include <cctype>
#include <string>
#include <vector>
#include <unordered_set>
namespace sandwich {
///////////////////////////////////////////
// DECLARATIONS //
///////////////////////////////////////////
/* Node struct
*
* This node struct is what is used as nodes in the
* trie class. Each node has a character value, a bool
* so that we may tell if all the nodes leading up to the
* current spell a valid string. The array of node pointers
* is what is used to store all possible children. Index 0
* represents an 'a' node, and index 25 represents 'z' node.
* Index 26 is a ' ' node.
*
* The node also holds a vector of generic data, used for storage
* and retrieval.
*/
template <typename T = char>
struct Node {
char value;
bool isWord;
bool isLeaf;
Node<T>* children[27];
std::vector<T> data;
// constructor / deconstructor
Node(const char value, const bool isWord);
~Node();
// Given a character, returns a pointer
// from the corresponding Node* index.
Node<T>* getChild(const char ch);
// Creates new node if it doesn't exist and returns
// a pointer to it. Otherwise, it just returns a pointer
// to the existing node
Node<T>* addChild(const char ch, const bool isWord);
// Add generic datum to data vector if it
// does not already hold it.
bool store(const T& datum);
// Remove datum from vector if it exists
void remove(const T& datum);
};
/* Trie class
*
* This class is used to autocomplete string,
* store data at a key, and retrieve data at a key.
*/
template <typename T = char>
class Trie {
Node<T>* root; // value = '\0', isWord = false;
public:
// Constructor / Destructor
Trie();
~Trie();
// Simply adds string to the trie structure.
// Returns true on success, false on failure
bool add(std::string key);
// Return true if the tree contains string.
// This search is not case sensitive.
bool search(std::string key);
// Complete: Give a string, this returns a vector
// of all the possible completions of the string.
std::vector<std::string> complete(std::string key = "");
// Store the datum at the end of each key given
// It only stores if the datum does not already exist
bool store(std::string key, const T& datum);
// Returns vector of data found at key location
std::vector<T> get(std::string key);
std::vector<T> get(std::vector<std::string> keys);
std::vector<T> getComplete(std::string key = "");
private:
// Preorder traversal:
// Current, left right
std::vector<std::string> preorder(Node<T>* node);
// Retrieval preorder
std::unordered_set<T> getPreorder(Node<T>* node);
// Used to sort the vector obtained from
// the unordered set
void insertionSort(std::vector<T>& vec);
};
///////////////////////////////////
// IMPLEMENTATIONS //
///////////////////////////////////
template <typename T>
Node<T>::Node(const char value, const bool isWord) :
value(value),
isWord(isWord),
isLeaf(true) {
for(int i = 0; i < 27; ++i) children[i] = nullptr;
}
template <typename T>
Node<T>::~Node() {
for(auto ptr : children) {
if(ptr != nullptr) delete ptr;
}
}
template <typename T>
Node<T>* Node<T>::getChild(const char ch) {
// Guard
if((!isalpha(ch) && ch != ' ') || isLeaf)
return nullptr;
// convert to index
int index = ch;
if(index == ' ') index = 26;
else {
if(index >= 'A' && index <= 'Z') {
index += 32;
}
index -= 'a';
}
return children[index];
}
template <typename T>
Node<T>* Node<T>::addChild(const char ch, const bool isWord){
// Guard
if(!isalpha(ch) && ch != ' ') return nullptr;
// Convert letter to index
int index = ch;
if(index == ' ') index = 26;
else {
if(index >= 'A' && index <= 'Z') {
index += 32;
}
index -= 'a';
}
// Add node if nonexistant, then return index
if(children[index] == nullptr) {
isLeaf = false;
children[index] = new Node<T>(ch, isWord);
}
return children[index];
}
template <typename T>
bool Node<T>::store(const T& datum) {
for(auto thing : data) {
if(thing == datum) return false;
}
data.push_back(datum);
return true;
}
template <typename T>
void Node<T>::remove(const T& datum) {
for(unsigned int i = 0; i < data.size(); ++i) {
if(datum == data[i]) {
data.erase(data.begin() + i);
}
}
}
///////////////////////////////////////////////
template <typename T>
Trie<T>::Trie() : root(new Node<T>('\0', false)) {}
template <typename T>
Trie<T>::~Trie() { delete root; }
template <typename T>
bool Trie<T>::add(std::string key) {
// Validate string / convert upper to lower
for(unsigned int i = 0; i < key.size(); ++i) {
if( !isalpha(key[i]) && key[i] != ' ') {
return false;
}
if(key[i] >= 'A' && key[i] <= 'Z') {
key[i] = key[i] + 32;
}
}
// Iterate through tree adding nodes
Node<T>* current = root;
Node<T>* next;
for(unsigned int i = 0; i < key.size(); ++i) {
int index = key[i];
if(index == ' ') index = 26;
else index -= 'a';
next = current->getChild(index);
if(next == nullptr) {
current = current->addChild(key[i], false);
}
else {
current = next;
}
}
if(current->isWord) return false;
else {
current->isWord = true;
return true;
}
}
template <typename T>
bool Trie<T>::search(std::string key) {
// Validate string
for(unsigned int i = 0; i < key.size(); ++i) {
if( !isalpha(key[i]) && key[i] != ' ') {
return false;
}
if(key[i] >= 'A' && key[i] <= 'Z') {
key[i] = key[i] + 32;
}
}
// Search through tree
Node<T>* node = root;
for(unsigned int i = 0; i < key.size(); ++i) {
node = node->getChild( key[i] );
if(node == nullptr) return false;
}
if(node->isWord) return true;
else return false;
}
/* ALGORITHM:
* 1. Navigate to the place where string given ends.
* 2. Work way down each branch until a leaf is reached.
* Along the way, any time we hit a word, add that component
* to the vector will the key string
*/
template <typename T>
std::vector<std::string> Trie<T>::complete(std::string key) {
std::vector<std::string> words;
// Guard / convert upper to lower
for(unsigned int i = 0; i < key.size(); ++i) {
if( !isalpha(key[i]) && key[i] != ' ') return words;
if(key[i] >= 'A' && key[i] <= 'Z') {
key[i] = key[i] + 32;
}
}
// Iterate to last node of the word
Node<T>* node = root;
for(unsigned int i = 0; i < key.size(); ++i) {
node = node->getChild( key[i] );
if(node == nullptr) return words;
}
// Add string if current node is a word
if(node->isWord) words.push_back(key);
// Call preorder on all children to get completion
for(unsigned int i = 0; i < 27; ++i) {
if(node->children[i] != nullptr) {
auto vec = preorder(node->children[i]);
for(auto substring : vec) {
words.push_back(key + substring);
}
}
}
return words;
}
template <typename T>
bool Trie<T>::store(std::string key, const T& datum) {
// Validate string / convert upper to lower
for(unsigned int i = 0; i < key.size(); ++i) {
if( !isalpha(key[i]) && key[i] != ' ') {
return false;
}
if(key[i] >= 'A' && key[i] <= 'Z') {
key[i] = key[i] + 32;
}
}
// Iterate through tree adding nodes
Node<T>* current = root;
Node<T>* next;
for(unsigned int i = 0; i < key.size(); ++i) {
int index = key[i];
if(index == ' ') index = 26;
else index -= 'a';
next = current->getChild(index);
if(next == nullptr) {
current = current->addChild(key[i], false);
}
else {
current = next;
}
}
// Mark the last node of they key string as a
// word, and store the data in the node's vector
current->isWord = true;
return current->store(datum);
}
template <typename T>
std::vector<T> Trie<T>::get(std::string key) {
// Validate string / convert upper to lower
for(unsigned int i = 0; i < key.size(); ++i) {
if( !isalpha(key[i]) && key[i] != ' ') {
return std::vector<T>();
}
if(key[i] >= 'A' && key[i] <= 'Z') {
key[i] = key[i] + 32;
}
}
// Iterate to the key node
Node<T>* node = root;
for(unsigned int i = 0; i < key.size(); ++i) {
int index = key[i];
if(index == ' ') index = 26;
else index -= 'a';
node = node->getChild( key[i] );
if(node == nullptr) return std::vector<T>();
}
return node->data;
}
template <typename T>
std::vector<T> Trie<T>::getComplete(std::string key) {
std::vector<T> dataVector;
std::unordered_set<T> dataSet;
// Verify key, convert to lower if necessary
for(unsigned int i = 0; i < key.size(); ++i) {
if(!isalpha(key[i]) && key[i] != ' ') {
return dataVector;
}
if(key[i] >= 'A' && key[i] <= 'Z') {
key[i] = key[i] + 32;
}
}
// Iterate to key subtree node
Node<T>* node = root;
for(unsigned int i = 0; i < key.size(); ++i) {
node = node->getChild( key[i] );
if(node == nullptr) return dataVector;
}
// Add current data if it exists
if(node->isWord) {
for(const auto& datum : node->data) {
dataSet.insert(datum);
}
}
// Add data from all subtree nodes if they do not
// already exist in the current dataSet.
for(unsigned int i = 0; i < 27; ++i) {
if(node->children[i] != nullptr) {
auto subSet = getPreorder(node->children[i]);
for(const auto& datum : subSet) {
dataSet.insert(datum);
}
}
}
// Copy set elements into vector
for(const auto& datum : dataSet) {
dataVector.push_back(datum);
}
return dataVector;
}
/* This traverses the tree in a preorder fashion.
* TODO: Improve efficiency and runtime
*/
template <typename T>
std::vector<std::string> Trie<T>::preorder(Node<T>* node) {
std::vector<std::string> words;
if(node == nullptr);
else if(node->isLeaf) {
std::string substring(1, node->value);
words.push_back(substring);
}
else {
// Push back current value if current node is a word
if(node->isWord) {
std::string substring(1, node->value);
words.push_back(substring);
}
// Append string from beneath to current node
for(unsigned int i = 0; i < 27; ++i) {
if(node->children[i] != nullptr) {
auto vec = preorder(node->children[i]);
for(auto rightstring : vec) {
std::string substring(1, node->value);
substring += rightstring;
words.push_back(substring);
}
}
}
}
return words;
}
template <typename T>
std::unordered_set<T> Trie<T>::getPreorder(Node<T>* node) {
std::unordered_set<T> dataSet;
if(node == nullptr);
else {
if(node->isWord) {
for(auto datum : node->data) {
dataSet.insert(datum);
}
}
for(unsigned int i = 0; i < 27; ++i) {
if(node->children[i] != nullptr) {
auto subSet = getPreorder(node->children[i]);
for(const auto& datum : subSet) {
dataSet.insert(datum);
}
}
}
}
return dataSet;
}
template <typename T>
void Trie<T>::insertionSort(std::vector<T>& vec) {
for(unsigned int i = 1; i < vec.size(); ++i) {
T datum = vec[i];
unsigned int j = i - 1;
while(j >= 0 && *datum < *vec[j]) {
vec[j + 1] = vec[j];
--j;
}
vec[j + 1] = datum;
}
}
} // namespace sandwich
#endif // SANDWICH_TRIE_H_