· 4 years ago · Mar 17, 2021, 07:32 PM
1/*
2#include <stdio.h>
3int main()
4{
5 unsigned int x = 0;
6 x=x-1;
7 printf("%u\n", x);
8}
9*/
10#include <stdbool.h>
11#include <ctype.h>
12#include <stdio.h>
13#include <stdlib.h>
14// Number of buckets in hash table
15const unsigned int N = 26;
16// Represents a node in a hash table
17typedef struct TrieNode
18{
19 char data;
20 int is_leaf;
21 struct TrieNode *children[N];
22}
23TrieNode;
24
25
26
27unsigned int counterWord = 0;
28
29TrieNode* DictRoot;
30
31char word[46];
32
33TrieNode* make_trienode(char data)
34{
35 // Allocate memory for a TrieNode
36 TrieNode *node = (TrieNode*) calloc (1, sizeof(TrieNode));
37 for (int i=0; i<N; i++)
38 {
39 node->children[i] = NULL;
40 }
41 node->is_leaf = 0;
42 node->data = data;
43 return node;
44}
45
46TrieNode* insert_trie(TrieNode* root, char* wordtemp)
47{
48 // Inserts the word onto the Trie
49 // ASSUMPTION: The word only has lower case characters
50 TrieNode* temp = root;
51
52 for (int i=0; wordtemp[i] != '\0'; i++)
53 {
54 // Get the relative position in the alphabet list
55 int idx = (int) wordtemp[i] - 'a';
56 if (temp->children[idx] == NULL)
57 {
58 // If the corresponding child doesn't exist,
59 // simply create that child!
60 temp->children[idx] = make_trienode(wordtemp[i]);
61 }
62 else {
63 // Do nothing. The node already exists
64 }
65 // Go down a level, to the child referenced by idx
66 // since we have a prefix match
67 temp = temp->children[idx];
68 }
69 // At the end of the word, mark this node as the leaf node
70 temp->is_leaf = 1;
71 return root;
72}
73void print_trie(TrieNode* root)
74{
75 // Prints the nodes of the trie
76 if (!root)
77 return;
78 TrieNode* temp = root;
79 printf("%c -> ", temp->data);
80 for (int i=0; i<N; i++) {
81 print_trie(temp->children[i]);
82 }
83}
84
85void free_trienode(TrieNode* node)
86{
87 // Free the trienode sequence
88 for(int i=0; i<N; i++) {
89 if (node->children[i] != NULL) {
90 free_trienode(node->children[i]);
91 }
92 else {
93 continue;
94 }
95 }
96 free(node);
97}
98int main()
99{
100 char * strii = "Week_5/pset5/speller/dictionaries/small";
101 FILE *dict = fopen(strii, "r");
102 if (dict == NULL)
103 {
104 printf("File can not open");
105 return 1;
106 }
107 while (fscanf(dict, "%s", word) != EOF)
108 {
109
110 fscanf(dict, "%s", word);
111 insert_trie(DictRoot, word);
112 counterWord++;
113 }
114
115 print_trie(DictRoot);
116 free_trienode(DictRoot);
117}