-
Notifications
You must be signed in to change notification settings - Fork 18
/
Trie.c
813 lines (608 loc) · 21 KB
/
Trie.c
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
#include "../Headers/Trie.h"
#include "../../Lists/Headers/ArrayList.h"
#include "../../Strings/Headers/String.h"
#include "../../../System/Utils.h"
#include "../../../Unit Test/CuTest/CuTest.h"
#include <math.h>
/** @struct Node
* @brief This structure implements a basic trie node.
* @var Trie::characters
* Member 'characters' is a pointer to characters nodes array.
* @var Trie::value
* Member 'value' holds the nodes value.
* @var Trie::EOW
* Member 'EOW' is a boolean to hold if the node us an end of a word or not.
*/
typedef struct TrieNode {
struct TrieNode **characters;
char value;
int EOW;
} TrieNode;
/** This struct will be useful in generating the best sequence in suggesting the words.*/
typedef struct KeyHolder {
char c;
float weight;
} KeyHolder;
void freeFun(void *item);
char toLowerCase(char c);
TrieNode *createNode(char value, int EOW);
void freeNode(TrieNode *node);
int nodeHasChildren(TrieNode *node);
TrieNode *trieRemoveWordR(TrieNode *root, const char *currentChar);
void trieAutoCompletionR(TrieNode *root, char *currentChar, int numOfSuggestion, String *string, ArrayList *wordsList);
void trieSuggestionR(TrieNode *root, char *word, String *string, ArrayList *wordsList, int numOfSuggestion);
void triePrintAllWordsR(TrieNode *root, String *string, FILE *dir);
int *generateIndices(char c);
TrieNode *destroyTrieNodes(TrieNode *root);
int wordsComparator(const void *word1, const void *word2);
/** This function will initialize a new trie in the memory, and initialize it's fields then,
* the function will return it's address.
*
* @return it will return the initialized trie address
*/
Trie *trieInitialization() {
Trie *trie = (Trie *) malloc(sizeof(Trie));
if (trie == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = FAILED_ALLOCATION;
return NULL;
#else
fprintf(stderr, FAILED_ALLOCATION_MESSAGE, "trie", "trie data structure");
exit(FAILED_ALLOCATION);
#endif
}
trie->root = createNode('\0', 0);
return trie;
}
/** This function will take the trie address, and the word address as a parameters,
* then it will add the word into the trie.
*
* @param trie the trie address
* @param word the word address
*/
void trieAddWord(Trie *trie, char *word) {
if (trie == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = NULL_POINTER;
return;
#else
fprintf(stderr, NULL_POINTER_MESSAGE, "trie", "trie data structure");
exit(NULL_POINTER);
#endif
} else if (word == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = INVALID_ARG;
return;
#else
fprintf(stderr, INVALID_ARG_MESSAGE, "word", "trie data structure");
exit(INVALID_ARG);
#endif
}
char *currentChar = word;
TrieNode *root = trie->root;
int index;
while (*currentChar != '\0') {
index = toLowerCase(*currentChar) - 'a';
if (index >= 0 && index < 26) {
if (root->characters[index] != NULL)
root = root->characters[index];
else
root = root->characters[index] = createNode(*currentChar, 0);
}
currentChar++;
}
root->EOW = 1;
}
/** This function will take the trie address, and the word address as a parameter,
* then it will return one (1) if the word is in the trie,
* other wise it will return zero (0).
*
* @param trie the trie address
* @param word the word address
* @return it will return one if the word is in the trie, other wise it will return zero
*/
int trieContains(Trie *trie, char *word) {
if (trie == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = NULL_POINTER;
return -1;
#else
fprintf(stderr, NULL_POINTER_MESSAGE, "trie", "trie data structure");
exit(NULL_POINTER);
#endif
} else if (word == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = INVALID_ARG;
return -1;
#else
fprintf(stderr, INVALID_ARG_MESSAGE, "word", "trie data structure");
exit(INVALID_ARG);
#endif
}
char *currentChar = word;
TrieNode *root = trie->root;
while (*currentChar != '\0') {
int index = toLowerCase(*currentChar) - 'a';
if (index >= 0 && index < 26) {
if (root->characters[index] != NULL)
root = root->characters[toLowerCase(*currentChar) - 'a'];
else
return 0;
}
currentChar++;
}
return root->EOW;
}
/** This function will take the trie address, and the word address as a parameters,
* then it will remove the given word from the trie.
*
* @param trie the trie address
* @param word the word address
*/
void trieRemoveWord(Trie *trie, char *word) {
if (trie == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = NULL_POINTER;
return;
#else
fprintf(stderr, NULL_POINTER_MESSAGE, "trie", "trie data structure");
exit(NULL_POINTER);
#endif
} else if (word == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = INVALID_ARG;
return;
#else
fprintf(stderr, INVALID_ARG_MESSAGE, "word", "trie data structure");
exit(INVALID_ARG);
#endif
}
TrieNode *root = trie->root;
int index = toLowerCase(*word) - 'a';
if (index >= 0 && index < 26) {
if (root->characters[index] != NULL)
trie->root->characters[index] = trieRemoveWordR(root->characters[index], word + 1);
}
}
/** This function takes the root node address, and the current char address as a parameters,
* then it will remove the given word from the trie recursively.
*
* Note: this function will be only called from the trieRemoveWord function only.
*
* @param root the node address
* @param currentChar the current char address
* @return it will return the node address to it's parent
*/
TrieNode *trieRemoveWordR(TrieNode *root, const char *currentChar) {
if (*currentChar == '\0') {
if (root->EOW) {
root->EOW = 0;
if (!nodeHasChildren(root)) {
freeNode(root);
return NULL;
}
}
return root;
}
int index = toLowerCase(*currentChar) - 'a';
if (index < 0 || index >= 26) {
return root;
}
if (root->characters[index] != NULL)
root->characters[index] = trieRemoveWordR(root->characters[index], currentChar + 1);
else
return root;
if (!nodeHasChildren(root) && !root->EOW) {
freeNode(root);
return NULL;
}
return root;
}
/** This function will be useful to initialize the array lists that will be returned to the user,
* after suggesting the words.
*
* @param word1 the first word pointer
* @param word2 the second word pointer
* @return
*/
int wordsComparator(const void *word1, const void *word2) {
return strcmp((char *) word1, (char *) word2);
}
/** This function will take the trie address, the word address, and the number of suggestion needed as a parameters,
* then it will return and array list pointer that contains all the words.
*
* Note: if the given word is wrong Linguistically then,
* the function will start to complete starts from the first wrong character.
*
* @param trie the trie address
* @param word the word address
* @param numOfSuggestion the number of wanted suggestion
* @return it will return an ArrayList address consisting the suggested words
*/
ArrayList *trieAutoCompletion(Trie *trie, char *word, int numOfSuggestion) {
if (trie == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = NULL_POINTER;
return NULL;
#else
fprintf(stderr, NULL_POINTER_MESSAGE, "trie", "trie data structure");
exit(NULL_POINTER);
#endif
} else if (word == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = INVALID_ARG;
return NULL;
#else
fprintf(stderr, INVALID_ARG_MESSAGE, "word", "trie data structure");
exit(INVALID_ARG);
#endif
} else if (numOfSuggestion <= 0) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = INVALID_ARG;
return NULL;
#else
fprintf(stderr, INVALID_ARG_MESSAGE, "number of suggestions", "trie data structure");
exit(INVALID_ARG);
#endif
}
ArrayList *wordsList = arrayListInitialization(numOfSuggestion, freeFun, wordsComparator);
String *string = stringInitialization(10);
trieAutoCompletionR(trie->root, word, numOfSuggestion, string, wordsList);
destroyString(string);
return wordsList;
}
/** This function will take the the root node, the current char address,
* the number of needed suggestion words,
* a string address, and an array list to put the words in it, as a parameters,
* then it will fill the array list with the words.
*
* Note: this function should be called by the trieAutoCompletion function only.
*
* @param root the node address
* @param currentChar the current char address
* @param numOfSuggestion the number of wanted suggestions
* @param string an initialized String address
* @param wordsList an initialized ArrayList address
*/
void trieAutoCompletionR(TrieNode *root, char *currentChar, int numOfSuggestion, String *string, ArrayList *wordsList) {
if (root->value != '\0')
stringAppendChar(string, root->value);
if (arrayListGetLength(wordsList) == numOfSuggestion)
return;
else if (root->EOW && *currentChar == '\0') {
char *word = stringToCharArray(string);
arrayListAdd(wordsList, word);
}
int index = toLowerCase(*currentChar) - 'a';
if (*currentChar != '\0' && root->characters[index] != NULL) {
trieAutoCompletionR(root->characters[index], currentChar + 1, numOfSuggestion, string, wordsList);
} else {
for (int i = 0; i < 26; i++) {
if (root->characters[i] != NULL) {
trieAutoCompletionR(root->characters[i], "\0", numOfSuggestion, string, wordsList);
}
}
}
if (stringGetLength(string) != 0)
stringRemove(string, stringGetLength(string) - 1);
}
/** This function will take the trie address, the word address, the number of needed words to be suggested as a parameters,
* then it will return an array list that contains the suggested words.
*
* @param trie the trie address
* @param word the word address
* @param numOfSuggestion the number of wanted suggestion
* @return it will return an array list consisting of the suggested words
*/
ArrayList *trieSuggestion(Trie *trie, char *word, int numOfSuggestion) {
if (trie == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = NULL_POINTER;
return NULL;
#else
fprintf(stderr, NULL_POINTER_MESSAGE, "trie", "trie data structure");
exit(NULL_POINTER);
#endif
} else if (word == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = INVALID_ARG;
return NULL;
#else
fprintf(stderr, INVALID_ARG_MESSAGE, "word", "trie data structure");
exit(INVALID_ARG);
#endif
} else if (numOfSuggestion <= 0) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = INVALID_ARG;
return NULL;
#else
fprintf(stderr, INVALID_ARG_MESSAGE, "number of suggestions", "trie data structure");
exit(INVALID_ARG);
#endif
}
String *string = stringInitialization(10);
ArrayList *wordsList = arrayListInitialization(numOfSuggestion, freeFun, wordsComparator);
trieSuggestionR(trie->root, word, string, wordsList, numOfSuggestion);
destroyString(string);
return wordsList;
}
/** This function will take the root node address, the words address, string address, array list address,
* and the number of words thar needed to be suggested as a parameter,
* then it will fill the array list with the words.
*
* Note: this function should only be called by the trieSuggestion function.
*
* @param root the node address
* @param word the word address
* @param string an initialized String address
* @param wordsList an initialized ArrayList address
* @param numOfSuggestion the number of wanted suggestion
*/
void trieSuggestionR(TrieNode *root, char *word, String *string, ArrayList *wordsList, int numOfSuggestion) {
if (root->value != '\0')
stringAppendChar(string, root->value);
if (*word == '\0') {
if (arrayListGetLength(wordsList) == numOfSuggestion)
return;
else if (root->EOW) {
char *finalWord = stringToCharArray(string);
arrayListAdd(wordsList, finalWord);
}
}
int *indices = generateIndices(toLowerCase(*word));
if (indices == NULL)
return;
for (int i = 0; i < 26; i++) {
if (root->characters[indices[i]] != NULL)
trieSuggestionR(root->characters[indices[i]], word + (*word == '\0' ? 0 : 1), string, wordsList,
numOfSuggestion);
}
free(indices);
if (stringGetLength(string) != 0)
stringRemove(string, stringGetLength(string) - 1);
}
/** This function will take the trie address as a parameter,
* then it will print all the words in the trie.
*
* @param trie the trie address
* @param dir the file pointer that the words will be printed in it
*/
void triePrintAllWords(Trie *trie, FILE *dir) {
if (trie == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = NULL_POINTER;
return;
#else
fprintf(stderr, NULL_POINTER_MESSAGE, "trie", "trie data structure");
exit(NULL_POINTER);
#endif
} else if (dir == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = INVALID_ARG;
return;
#else
fprintf(stderr, INVALID_ARG_MESSAGE, "file pointer", "trie data structure");
exit(INVALID_ARG);
#endif
}
String *string = stringInitialization(10);
for (int i = 0; i < 26; i++) {
if (trie->root->characters[i] != NULL)
triePrintAllWordsR(trie->root->characters[i], string, dir);
}
destroyString(string);
}
/** This function will take the root node address, and a string address as a parameter,
* then it will print all the words in the trie.
*
* Note: this function should only be called from the triePrintAllWords function.
*
* @param root the node address
* @param string an initialized String address
* @param dir the file pointer that the words will be printed in it
*/
void triePrintAllWordsR(TrieNode *root, String *string, FILE *dir) {
stringAppendChar(string, root->value);
if (root->EOW) {
printString(string, dir);
fprintf(dir, "\n");
}
for (int i = 0; i < 26; i++) {
if (root->characters[i] != NULL)
triePrintAllWordsR(root->characters[i], string, dir);
}
stringRemove(string, stringGetLength(string) - 1);
}
/** This function will take the trie address as a parameter,
* then it will clear and free all the trie nodes,
* without destroying the trie.
*
* @param trie the trie address
*/
void clearTrie(Trie *trie) {
if (trie == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = NULL_POINTER;
return;
#else
fprintf(stderr, NULL_POINTER_MESSAGE, "trie", "trie data structure");
exit(NULL_POINTER);
#endif
}
for (int i = 0; i < 26; i++) {
if (trie->root->characters[i] != NULL)
trie->root->characters[i] = destroyTrieNodes(trie->root->characters[i]);
}
}
/** This function will take the trie address as a parameter,
* then it will destroy and free the trie and all it's nodes.
*
* @param trie the trie address
*/
void destroyTrie(void *trie) {
if (trie == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = NULL_POINTER;
return;
#else
fprintf(stderr, NULL_POINTER_MESSAGE, "trie", "trie data structure");
exit(NULL_POINTER);
#endif
}
Trie *trieToFree = (Trie *) trie;
trieToFree->root = destroyTrieNodes(trieToFree->root);
free(trie);
}
/** This function takes the root node address as a parameter,
* then it will destroy and free all the nodes.
*
* Note: This should only be called from the clearTrie and destroyTrie functions.
*
* @param root the node address
* @return it will return NULL to the node parent
*/
TrieNode *destroyTrieNodes(TrieNode *root) {
for (int i = 0; i < 26; i++) {
if (root->characters[i] != NULL)
root->characters[i] = destroyTrieNodes(root->characters[i]);
}
freeNode(root);
return NULL;
}
/** This function takes a character as a parameter,
* then it will return the lower case of the of the character if it's an alphabet.
*
* Note: this function private to be used by the tries function only.
*
* @param c the character
* @return it will return the character in lower case
*/
char toLowerCase(char c) {
if (c >= 'A' && c <= 'Z')
return (char) ((int) c + 32);
return c;
}
/** This function will take a node address as a parameter,
* then it will return one (1) if the node has al least one child,
* other wise it will return zero (0).
*
* Note: This function is private to be used by the trie functions only.
*
* @param node the node address
* @return it will return one if the node hash children, other wise it will return zero
*/
int nodeHasChildren(TrieNode *node) {
for (int i = 0; i < 26; i++) {
if (node->characters[i] != NULL)
return 1;
}
return 0;
}
/** This function will take a character, and an end of word boolean as a parameters,
* then it will return a new node address that has been initialized with the passed values.
*
* Note: this function should be only called from the inside of the trie.
*
* @param value the node character
* @param EOW the end of word boolean
* @return it will return a new initialized node address
*/
TrieNode *createNode(char value, int EOW) {
TrieNode *node = (TrieNode *) malloc(sizeof(TrieNode));
if (node == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = FAILED_ALLOCATION;
return NULL;
#else
fprintf(stderr, FAILED_ALLOCATION_MESSAGE, "new node", "trie data structure");
exit(FAILED_ALLOCATION);
#endif
}
node->characters = (TrieNode **) calloc(sizeof(void *), 26);
if (node->characters == NULL) {
#ifdef C_DATASTRUCTURES_ERRORSTESTSTRUCT_H
ERROR_TEST->errorCode = FAILED_ALLOCATION;
return NULL;
#else
fprintf(stderr, FAILED_ALLOCATION_MESSAGE, "new node characters array", "trie data structure");
exit(FAILED_ALLOCATION);
#endif
}
node->value = value;
node->EOW = EOW;
return node;
}
/** This function will take a node address as a parameter,
* then it will destroy and free that node.
*
* Note: this function should be only called from the inside if the trie.
*
* @param node the node address
*/
void freeNode(TrieNode *node) {
free(node->characters);
free(node);
}
/** This function is useful for the generateIndices function, to sort the keyHolder array*/
int comparator(const void *p1, const void *p2) {
float subVal = ((KeyHolder *) p1)->weight - ((KeyHolder *) p2)->weight;
return subVal >= 0 ? (int) ceilf(subVal) : (int) floorf(subVal);
}
/** This function will take a character as a parameter,
* then it will generate a list of indices that depends on the distance between keys in the keyboard,
* and return it as an integer array.
*
* @param c the character value
* @return it will return an array of indices
*/
int *generateIndices(char c) {
int *arr = (int *) malloc(sizeof(int) * 26);
if (c == '\0') {
for (int i = 0; i < 26; i++)
arr[i] = i;
return arr;
} else if (!(c >= 'a' && c <= 'z')) {
return NULL;
}
char matrix[3][10] = {
{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'},
{'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', '\0'},
{'z', 'x', 'c', 'v', 'b', 'n', 'm', '\0', '\0', '\0'}
};
int row = 0, col = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 10; j++) {
if (matrix[i][j] == c) {
row = i;
col = j;
break;
}
}
if (row && col || (!row && !col && c == 'q'))
break;
}
int keyIndex = 0;
KeyHolder keys[26];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 10; j++) {
if (matrix[i][j] == '\0')
continue;
keys[keyIndex].c = matrix[i][j];
float pow1 = powf((float) i - (float) row, 2);
float pow2 = powf((float) j - (float) col, 2);
float root = sqrtf(pow1 + pow2);
keys[keyIndex++].weight = root;
}
}
qsort(keys, 26, sizeof(KeyHolder), comparator);
for (int i = 0; i < 26; i++) {
arr[i] = keys[i].c - 'a';
}
return arr;
}
/** The free function that will free the words in the array list that will be returned to the user,
* holding the suggested words.
*/
void freeFun(void *item) {
free((char *) item);
}