-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhywrong.c
159 lines (138 loc) · 2.77 KB
/
whywrong.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
// Implements a dictionary's functionality
#include <stdbool.h>
#include<cs50.h>
#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
#include "dictionary.h"
typedef struct node
{
bool is_word;
struct node *children[27];
}
node;
node *root;
int counter = 0;
node *getNode(void)
{
node *newNode = malloc(sizeof(node));
if (newNode != NULL)
{
newNode->is_word = false;
for (int i = 0; i < 27; i++)
{
newNode->children[i] = NULL;
}
}
return newNode;
}
void freeSpace(node* end)
{
for (int i = 0; i < 27; i++)
{
if(end->children[i] != NULL)
{
freeSpace(end->children[i]);
}
}
free(end);
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
node* pointer = root;
int num = 0;
bool isword = false;
for (int i = 0; word[i] != '\0'; i++) ??
{
if (isalpha(word[i])) ??
{
num = tolower(word[i]) - 'a';
}
else if(word[i] == '\'')
{
num = 26;
}
printf("%i\n",num);
pointer = pointer->children[num];
if(pointer == NULL)
{
return false;
}
}
isword = pointer->is_word;
return isword;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
int num = 0;
root = getNode();
if(root == NULL)
{
return false;
}
FILE *dic = fopen(dictionary,"r");
if (dic == NULL)
{
printf("File does not exist.\n");
return false;
}
for(int c = fgetc(dic); c != EOF; c = fgetc(dic))
{
node* pointer = root;
if (c != '\n')
{
if (isalpha(c))
{
num = c - 'a';
}
else if(c == '\'')
{
num = 26;
}
if (pointer->children[num] == NULL)
{
pointer->children[num] = getNode();
if (pointer->children[num] == NULL)
{
return false;
}
}
pointer = pointer->children[num];
}
else
{
pointer->is_word = true;
counter++;
}
}
fclose(dic);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
if (counter > 0)
{
return counter;
}
else
{
return 0;
}
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
if(root != NULL)
{
node* pointer = root;
freeSpace(pointer);
return true;
}
else
{
return false;
}
}