-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdictionary.c
146 lines (134 loc) · 2.63 KB
/
dictionary.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
/**
* Implements a dictionary's functionality.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define LOWERCASE_A 97
#define APOSTROPHE 26
#include "dictionary.h"
typedef struct _trie
{
bool isWord;
struct _trie *children[27];
} node ;
// Declare root node
node *root;
int dicWordCount = 0;
/**
* Returns the index of a letter in a node
*/
int getindex(const char ch)
{
if(ch == '\'')
return APOSTROPHE;
else
return tolower(ch) - LOWERCASE_A ;
}
/**
* Create nodes for trie
*/
node* create()
{
node *temp = (node*) malloc(sizeof(node));
for(int i = 0; i <= APOSTROPHE; i++)
{
temp->children[i] = NULL;
}
temp->isWord = NULL;
return temp;
}
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char *word)
{
node *trav = root;
int index;
for(int i = 0; word[i] != '\0'; i++)
{
index = getindex(word[i]);
trav = trav->children[index];
if(trav == NULL)
{
return false;
}
}
return trav->isWord;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char *dictionary)
{
FILE *inptr = fopen(dictionary,"r");
root = create();
char word[45];
int index;
node *newNode;
while(feof(inptr) == 0)
{
fscanf(inptr, "%s", word);
newNode = root;
for(int i = 0; word[i] != '\0'; i++)
{
index = getindex(word[i]);
if(newNode->children[index] == NULL)
{
newNode->children[index] = create();
if(newNode->children[index] == NULL)
{
return false;
}
}
newNode = newNode->children[index];
}
newNode->isWord = true;
dicWordCount++;
}
if (ferror(inptr))
{
fclose(inptr);
unload();
return false;
}
fclose(inptr);
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
return dicWordCount - 1;
}
/**
* Unloads trie from memory. Returns true if successful else false.
*/
void unloadtrie(node *n)
{
if(n == NULL)
{
return;
}
else
{
for(int i = 0; i <= APOSTROPHE; i++)
{
if(n->children[i] != NULL)
{
unloadtrie(n->children[i]);
}
}
free(n);
}
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
unloadtrie(root);
return true;
}