-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdictionary.c
More file actions
148 lines (119 loc) · 2.84 KB
/
Copy pathdictionary.c
File metadata and controls
148 lines (119 loc) · 2.84 KB
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
/**
* dictionary.c
*
* Computer Science 50
* Problem Set 5
*
* Implements a dictionary's functionality.
*/
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <ctype.h>
#include "dictionary.h"
#define TRIELENGTH 27
typedef struct node {
bool isWord;
struct node * next;
} node_t;
bool initialize (node_t * arr) {
int i;
for(i=0; i<TRIELENGTH; i++) {
arr[i].isWord = false;
arr[i].next = NULL;
}
return true;
}
void recursive (node_t * arr) {
int i;
for(i=0; i<TRIELENGTH; i++) {
if(arr[i].next != NULL) {
recursive(arr[i].next);
}
}
free(arr);
}
node_t * trie;
int words = 0;
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char* word)
{
int index, i = 0;
node_t * tempArray = trie;
while(word[i] != '\00') {
if(word[i] == '\'') {
index = 26;
}
else {
index = (int)(toupper(word[i])-'A'); //get trie index out of character
}
if(tempArray[index].next == NULL) {
return false;
}
tempArray = tempArray[index].next;
i++;
}
if(!tempArray[index].isWord) {
return false;
}
return true;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char* dictionary)
{
trie = malloc(sizeof(node_t)*TRIELENGTH);
FILE* inptr = fopen(dictionary, "r");
if(inptr == NULL) {
printf("Couldn't open a file!\n");
return false;
}
if(!initialize(trie)) {
printf("Couldn't initialize trie!\n");
return false;
}
char line[LENGTH+2]; //+2 for terminating sequence \n\00
int i, index;
node_t * tempArray;
while(fgets(line, sizeof(line), inptr)) {
tempArray = trie;
i=0;
while(line[i] != '\n') //lines ending with \n\00
{
if(line[i] == '\'') {
index = 26;
}
else {
index = (int)(toupper(line[i])-'A'); //get trie index out of character
}
if(tempArray[index].next == NULL) {
tempArray[index].next = malloc(TRIELENGTH*sizeof(node_t));
initialize(tempArray[index].next);
}
tempArray = tempArray[index].next;
i++;
}
tempArray[index].isWord = true;
words++;
}
fclose(inptr);
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
return words;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
recursive(trie);
return true;
}