-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdictionary.c
136 lines (120 loc) · 2.8 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
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "dictionary.h"
#include <string.h>
#include <ctype.h>
typedef struct node
{
bool isWord;
struct node *children[27];
}
node;
node *root = NULL;
int dictionarySize;
int charToInt(char c)
{
if (c == '\'')
{
return 26;
}
else
{
return (int) c - 97;
}
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
node *subWord = root;
const char *t;
for (t = word; *t != '\0'; t++)
{
int index = charToInt(tolower(*t));
if (subWord->children[index] == NULL)
{
return false;
}
subWord = subWord->children[index];
}
return (subWord->isWord);
}
void initialiseNode(node *node)
{
for (int i = 0; i < 27; i++)
{
node->children[i] = NULL;
}
node->isWord = false;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
dictionarySize = 0;
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
fprintf(stderr, "Could not open %s.\n", dictionary);
return 3;
}
char word[LENGTH + 1];
root = malloc(sizeof(node));
initialiseNode(root);
node *currentNode;
node *childNode;
// for each word in the dictionary file
while (fscanf(file, "%s", word) != EOF)
{
currentNode = root;
int index = 0;
while (word[index] != '\0')
{
int childIndex = charToInt(word[index++]);
// add child node if necessary
childNode = currentNode->children[childIndex];
if (childNode == NULL)
{
childNode = malloc(sizeof(node));
if (childNode == NULL)
{
fprintf(stderr, "malloc failed");
return false;
}
initialiseNode(childNode);
currentNode->children[childIndex] = childNode;
}
// advance to child node
currentNode = childNode;
}
// mark the end of the word
currentNode->isWord = true;
dictionarySize++;
}
fclose(file);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return dictionarySize;
return 0;
}
bool unloadNode(node *nodeToCheck)
{
for (int i = 0; i < 27; i++)
{
if (nodeToCheck->children[i] != NULL)
{
unloadNode(nodeToCheck->children[i]);
}
}
free(nodeToCheck);
return true;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
node *pointer = root;
return unloadNode(pointer);
}