-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.c
881 lines (685 loc) · 20.4 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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include "trie.h"
int COUNT = 0; // number of elements in trie
int main(int argc, char * argv[])
{
// driver code
if (argc != 2 && argc != 3)
{
printf("Please use as follows: ./trie [DICTIONARY] [TEXT] or ./trie [DICTIONARY]\n");
return 1;
}
trienode * root = initTrie();
char * dictionary = argv[1];
bool uploaded = upload(root, dictionary);
if (uploaded == false)
{
printf("Could not upload %s\n", dictionary);
return 1;
}
printTrie(root);
if (argc == 3)
{
char * sampletext = argv[2];
spell_check(root, sampletext);
}
prefixSearchPrompt(root);
prefixDeletePrompt(root);
freeTrie(root);
}
// main function for running tests
// int main(int argc, char * argv[])
// {
// if (argc != 2 && argc != 3)
// {
// printf("Please use as follows: ./trie [DICTIONARY] [TEXT] or ./trie [DICTIONARY]\n");
// return 1;
// }
// trienode * root = initTrie();
// char * dictionary = argv[1];
// // TESTS (Please run each separately)
// //insert_dict_then_delete(root, dictionary);
// //insert_dict_then_prefixdelete(root, dictionary);
// }
trienode * initTrie()
{
trienode * root = malloc(sizeof(struct trienode));
//check whether malloc successful
if (root == NULL)
{
printf("Error: Malloc failed\n");
return root;
}
for (int i = 0; i < N; i++)
{
root->next[i] = NULL;
root->endofword = false;
}
return root;
}
// the following code is for input which is made of english characters along with apostrophe
//inserts string of characters into trie
trienode * insertTrie(trienode * root, char * word)
{
if (root == NULL)
{
root = initTrie(); // root will be NULL only when all elements are deleted from a trie, then we need to assign root to insertTrie()
}
trienode * temp = root;
int length = strlen(word);
if (length > MAXWORDSIZE || length <= 0)
{
printf("Length of string should be >= 1 and <= %i\n", MAXWORDSIZE);
printf("Error string: '%s'\n\n", word);
return root;
}
for (int i = 0; i < length; i++)
{
if (isalpha(word[i]) == 0 && word[i] != '\'') // if a char is not alphabetical and not apostrophe
{
printf("Word must consist of english alphabets\n");
printf("Error string: '%s'\n\n", word);
return root;
}
word[i] = tolower(word[i]); // converts everything to lowercase
assert((word[i] >= 'a' && word[i] <= 'z') || word[i] == '\'');
int index;
if (word[i] == '\'') // apostrophe
{
index = 26; // apostrophe is mapped to the last index
}
else
{
index = word[i] - 97; // 97 corresponds to 'a' so if word[i] is z (ascii 122) then index will be 122-97 = 25
}
if (temp->next[index] == NULL) // if the letter value does not exist in the trienode
{
temp->next[index] = initTrie(); // create new trienode corresponding to the index
temp = temp->next[index]; // temp points to this new trie node
if (i == length - 1) // if we reached end of a string
{
temp->endofword = true;
}
}
else if (temp->next[index]) // if the letter value exists then move on to the next node
{
temp = temp->next[index];
if (i == length - 1)
{
temp->endofword = true; // for example if "antique" already there and we are inserting "anti"
}
}
}
COUNT++;
return root;
}
// searches for a word in the trie
bool searchTrie(trienode * root, char * word)
{
trienode * temp = root;
int length = strlen(word);
for (int i = 0; i < length; i++)
{
if (isalpha(word[i]) == 0 && word[i] != '\'')
{
printf("Word must consist of english alphabets\n");
printf("Error string: '%s'\n", word);
return false;
}
word[i] = tolower(word[i]);
assert((word[i] >= 'a' && word[i] <= 'z') || word[i] == '\'');
int index;
if (word[i] == '\'') // apostrophe
{
index = 26;
}
else
{
index = word[i] - 97;
}
if (temp->next[index]) // if it exists
{
if (i == length - 1 && temp->next[index]->endofword == true) // if we reached end of input string and the boolean endofword marker is true
{
printf("\nYES, the string '%s' exists in the trie\n", word);
return true;
}
else if (i == length - 1 && temp->next[index]->endofword == false) // if we reached end of string and boolean endofword marker is false
{
printf("\nNO, the string '%s' does not exist in the trie\n", word);
return false;
}
else if(i != length - 1) // if we haven't reached end of string yet
{
temp = temp->next[index];
}
}
else // if the letter value does not exist
{
printf("\nNO, the string '%s' does not exist in the trie\n", word);
return false;
}
}
}
bool simple_search_trie(trienode * root, char * word) // just returns true or false based on whether word is in trie or not, without printing anything
{
trienode * temp = root;
int length = strlen(word);
for (int i = 0; i < length; i++)
{
if (isalpha(word[i]) == 0 && word[i] != '\'')
{
return false;
}
word[i] = tolower(word[i]);
assert((word[i] >= 'a' && word[i] <= 'z') || word[i] == '\'');
int index;
if (word[i] == '\'') // apostrophe
{
index = 26;
}
else
{
index = word[i] - 97; // 97 corresponds to 'a' so if word[i] is z (ascii 122) then index will be 122-97 = 25
}
if (temp->next[index])
{
if (i == length - 1 && temp->next[index]->endofword == true) // if we reached end of input string and the boolean endofword marker is true
{
return true;
}
else if (i == length - 1 && temp->next[index]->endofword == false) // if we reached end of string and boolean endofword marker is false
{
return false;
}
else if(i != length - 1) // if we haven't reached end of string yet
{
temp = temp->next[index];
}
}
else
{
return false; // if the node corresponding to letter does not exist
}
}
}
// checks if a trienode has at least one child or not
bool no_children(trienode * root)
{
for (int i = 0; i < N; i++)
{
if (root->next[i] != NULL) // if any one of the children is not NULL then the trienode has at least one child
{
return false;
}
else
{
continue;
}
}
return true;
}
// deletes a word from the trie. Called with trie_level = 0
trienode * delete_from_trie(trienode * root, char * word, int trie_level)
{
if (root == NULL)
{
printf("Root is NULL\n");
return root;
}
if (trie_level == 0 && !simple_search_trie(root, word)) // searching for the word from the root
{
printf("The word '%s' is not in the trie\n", word);
return root;
}
int length = strlen(word);
if (trie_level == length) // if we reached last character in given word
{
if (root->endofword == true)
{
root->endofword = false; // setting endofword marker to false effectively deletes word from trie
COUNT--;
}
if (no_children(root)) // if the trienode has no children we can just free it and set it to NULL
{
free(root);
root = NULL;
}
// if the trienode has children and we reached the end of the word then nothing else to do since the endofword flag has already been set to false
return root;
}
// if we haven't reached the last character in the given word
int index;
assert((word[trie_level] >= 'a' && word[trie_level] <= 'z') || word[trie_level] == '\'');
if (word[trie_level] == '\'') // apostrophe
{
index = 26;
}
else
{
index = word[trie_level] - 97;
}
root->next[index] = delete_from_trie(root->next[index], word, trie_level + 1); // recursively delete
if (no_children(root) && root->endofword == false) // accounting for trienodes whose children have been deleted
{
free(root);
root = NULL;
}
return root;
}
bool is_leaf(trienode * root)
{
if (root->endofword == true)
{
return true;
}
else
{
return false;
}
}
void print_trie_helper(trienode * root, char buffer[], int level)
{
if (root == NULL)
{
return;
}
// if node is a leaf node, it indicates it is the end of some word so null char is added and word is printed
if (is_leaf(root))
{
buffer[level] = '\0';
printf("%s\n", buffer);
}
for (int i = 0; i < N; i++)
{
// if a child exists then add the corresponding parent character to the buffer
if (root->next[i])
{
if (i == 26)
{
buffer[level] = '\'';
}
else
{
buffer[level] = i + 'a'; // 'a' corresponds to 97
}
print_trie_helper(root->next[i], buffer, level + 1); // calling print function recursively on children
}
}
}
// prints trie in lexicographic order (Here alphabetical and with the apostrophe being the last character in the order after 'z')
void printTrie(trienode * root)
{
if (root == NULL)
{
printf("\nRoot of trie is NULL\n");
return;
}
printf("\nTrie: \n");
char buffer[MAXWORDSIZE+1];
print_trie_helper(root, buffer, 0); // since we start from level 0 of the trie
}
// given a string input like "ca", it finds all the words starting with those letters
bool prefix_search(trienode * root, char * word)
{
if (root == NULL)
{
return false;
}
trienode * temp = root;
int length = strlen(word);
for (int i = 0; i < length; i++)
{
if (isalpha(word[i]) == 0 && word[i] != '\'')
{
printf("Prefix must contain all alphabetical english letters\n");
return false;
}
word[i] = tolower(word[i]);
assert((word[i] >= 'a' && word[i] <= 'z') || word[i] == '\'');
int index;
if (word[i] == '\'') // apostrophe
{
index = 26;
}
else
{
index = word[i] - 97;
}
if (temp->next[index])
{
if (i == length - 1)
{
printf("\nWords starting with prefix '%s' in dictionary: \n", word);
prefix_print(temp->next[index], word);
return true;
}
else if (i != length - 1)
{
temp = temp->next[index];
}
}
else
{
printf("\nPrefix '%s' does not exist\n", word);
return false;
}
}
}
// prints words starting with given prefix
void prefix_print(trienode * temp, char * prefix)
{
int length = strlen(prefix);
char buffer[MAXWORDSIZE + 1 + length];
for (int i = 0; i < length; i++)
{
buffer[i] = prefix[i];
}
// now the buffer has the prefix and can be used to add all the suffixes in the helper function
helper_prefix_print(temp, length, buffer);
}
void helper_prefix_print(trienode * root, int level, char buffer[])
{
if (is_leaf(root))
{
buffer[level] = '\0';
printf("%s\n", buffer);
}
for (int i = 0; i < N; i++)
{
if (root->next[i])
{
if (i == 26)
{
buffer[level] = '\'';
}
else
{
buffer[level] = i + 'a';
}
print_trie_helper(root->next[i], buffer, level + 1);
}
}
}
// delete all words starting with given prefix
int prefix_delete(trienode * root, char * prefix)
{
if (root == NULL)
{
return 1;
}
trienode * temp = root;
int length = strlen(prefix);
for (int i = 0; i < length; i++)
{
if (isalpha(prefix[i]) == 0 && prefix[i] != '\'')
{
printf("Prefix must contain all alphabetical english letters\n");
return 2;
}
prefix[i] = tolower(prefix[i]);
assert((prefix[i] >= 'a' && prefix[i] <= 'z') || prefix[i] == '\'');
int index;
if (prefix[i] == '\'') // apostrophe
{
index = 26;
}
else
{
index = prefix[i] - 97;
}
if (temp->next[index])
{
if (i == length - 1)
{
freeTrie(temp->next[index]);
temp->next[index] = NULL;
return 0;
}
else if (i != length - 1)
{
temp = temp->next[index];
}
}
else
{
printf("Prefix '%s' does not exist\n", prefix);
return 3;
}
}
}
// upload the dictionary into the trie word by word
bool upload(trienode * root, char * dictionary)
{
if (wrong_file_format(root, dictionary) == 0) // check whether the file extension is .txt
{
return false;
}
int len = strlen(dictionary);
assert(dictionary[len-1] == 't');
assert(dictionary[len-2] == 'x');
assert(dictionary[len-3] == 't');
assert(dictionary[len-4] == '.');
FILE *dict = fopen(dictionary, "r");
if (dict == NULL)
{
printf("Could not open %s\n", dictionary);
return false;
}
char word_buffer[MAXWORDSIZE+1];
while(fscanf(dict, "%s", word_buffer) != EOF) // scans and puts words in buffer word by word until EOF is reached
{
insertTrie(root, word_buffer);
}
fclose(dict);
return true;
}
trienode * freeTrie(trienode * root)
{
if (root == NULL)
{
return root;
}
for (int i = 0; i < N; i++)
{
if (root->next[i] != NULL)
{
freeTrie(root->next[i]); // recursively free children
}
}
free(root); // after freeing children, free the root and set it to NULL
root = NULL;
return root;
}
// reads input string character by character to save space and checks for validity
char * input_string(void)
{
char * buffer = malloc(sizeof(char));
int c;
int buffer_size = 0;
int buffer_cap = 0;
while ((c = fgetc(stdin)) != '\r' && c != '\n' && c != EOF)
{
if (buffer_size + 1 > buffer_cap) // dynamically increase buffer size if it is needed
{
if (buffer_cap < MAXWORDSIZE + 1) // increase buffer cap if possible
{
buffer_cap++;
}
else
{
free(buffer);
return NULL;
}
char * temp = realloc(buffer, buffer_cap); // reallocate memory to increase buffer capacity
if (temp == NULL)
{
free(buffer);
return NULL;
}
buffer = temp;
}
buffer[buffer_size++] = c; // append current char to buffer and then increments buffer size
}
// check if no input given
if (buffer_size == 0 && c == EOF)
{
return NULL;
}
if (buffer_size == MAXWORDSIZE + 1)
{
free(buffer);
return NULL;
}
char * mystring = realloc(buffer, buffer_size + 1);
if (mystring == NULL)
{
free(buffer);
return NULL;
}
mystring[buffer_size] = '\0';
return mystring;
}
void prefixSearchPrompt(trienode * root)
{
printf("Enter prefix: ");
char * prefix = input_string();
if (prefix == NULL)
{
printf("Invalid input\n");
return;
}
printf("Prefix: %s\n", prefix);
bool search = prefix_search(root, prefix);
free(prefix);
}
void prefixDeletePrompt(trienode * root)
{
printf("Delete all words starting with given prefix: ");
char * prefix = input_string();
if (prefix == NULL)
{
printf("Invalid input\n");
return;
}
printf("Prefix: %s\n", prefix);
bool search = prefix_search(root, prefix);
prefix_delete(root, prefix);
printf("\nAfter deletion: \n");
prefix_search(root, prefix);
printTrie(root);
free(prefix);
}
void spell_check(trienode * root, char * text)
{
int len = strlen(text);
if (wrong_file_format(root, text) == 0)
{
return;
}
assert(text[len-1] == 't'); // check whether the file extension is .txt
assert(text[len-2] == 'x');
assert(text[len-3] == 't');
assert(text[len-4] == '.');
FILE *samptext = fopen(text, "r");
if (samptext == NULL)
{
printf("\nCouldn't open or find text file to check\n");
return;
}
int index = 0;
int wrongspellings = 0;
int words = 0;
char word[MAXWORDSIZE];
char c;
printf("\nWords misspelled:\n");
while (fread(&c, sizeof(char), 1, samptext))
{
if (isalpha(c) || (c == '\'' && index > 0)) // apostrophe can't be the first character in correctly spelled word in this case
{
// make the word character by character
word[index] = c;
index++;
if (index > MAXWORDSIZE-1) // ignore words that are too big
{
while (fread(&c, sizeof(char), 1, samptext) && isalpha(c)); // goes to next word
index = 0; // Prepare for new wordx
}
}
// ignore words with numbers
else if (isdigit(c))
{
while (fread(&c, sizeof(char), 1, samptext) && isalpha(c)); // goes to next word
index = 0;
}
else if (index > 0) // we have found a whole word
{
word[index] = '\0';
words++;
// Print word if wrong spelling and increment number of wrong spellings
if (simple_search_trie(root, word) == false)
{
printf("%s\n", word);
wrongspellings++;
}
index = 0;
}
}
fclose(samptext);
printf("\nNumber of words misspelled: %d\n", wrongspellings);
printf("Number of words in dictionary: %d\n", COUNT);
printf("Number of words in the text: %d\n", words);
return;
}
// TESTS
int insert_dict_then_delete(trienode * root, char * dictionary)
{
bool uploaded = upload(root, dictionary);
if (uploaded == false)
{
printf("Could not upload %s\n", dictionary);
return 1;
}
//printTrie(root);
freeTrie(root);
root = NULL;
printf("\nAfter deletion of trie:\n");
printTrie(root);
return 0;
}
int insert_dict_then_prefixdelete(trienode * root, char * dictionary)
{
bool uploaded = upload(root, dictionary);
if (uploaded == false)
{
printf("Could not upload %s\n", dictionary);
return 1;
}
prefixDeletePrompt(root);
}
int wrong_file_format(trienode * root, char * text)
{
int length = strlen(text);
for (int i = 0; i < length; i++)
{
text[i] = tolower(text[i]);
}
int c1 = text[length-1];
int c2 = text[length-2];
int c3 = text[length-3];
int c4 = text[length-4];
if (c1 == 116 && c2 == 120 && c3 == 116 && c4 == 46)
{
return 1;
}
else
{
printf("\nPlease use a .txt file\n");
return 0;
}
}