-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdictionary.c
125 lines (110 loc) · 2.53 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
// Implements a dictionary's functionality
#include <stdbool.h>
#include<ctype.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
#define HASHTABLE_SIZE 1000
// Number of buckets in hash table
// Hash table
node *table[HASHTABLE_SIZE];
unsigned int num_words=0;
bool is_loaded_dict=false;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
char check_word[strlen(word)];
strcpy(check_word,word);
for(int i=0;check_word[i]!='\0';i++)
{
check_word[i]=tolower(check_word[i]);
}
int index=hash(check_word);
if(table[index]!=NULL)
{
for(node* nodeptr=table[index];nodeptr!=NULL;nodeptr=nodeptr->next)
if(strcmp(nodeptr->word,check_word)==0)
return true;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
int hash=0;
int n;
for(int i=0;word[i]!='\0';i++)
{
if(isalpha(word[i]))
n=word[i]-'a'+1;
else
n=27;
hash = ((hash<<3)+n)%HASHTABLE_SIZE;
}
return hash;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
FILE* infile=fopen(dictionary,"r");
if(infile==NULL)
return false;
for(int i=0;i<HASHTABLE_SIZE;i++)
{
table[i]=NULL;
}
char word[LENGTH+1];
node* new_nodeptr;
while(fscanf(infile,"%s",word)!=EOF)
{
num_words++;
do
{
new_nodeptr=malloc(sizeof(node));
if(new_nodeptr==NULL)
free(new_nodeptr);
}while(new_nodeptr==NULL);
strcpy(new_nodeptr->word,word);
int index=hash(word);
new_nodeptr->next=table[index];
table[index]=new_nodeptr;
}
fclose(infile);
is_loaded_dict=true;
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
if(!(is_loaded_dict))
return 0;
return num_words;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
if(!is_loaded_dict)
return false;
for(int i=0;i<HASHTABLE_SIZE;i++)
{
if(table[i]!=NULL)
{
node* ptr=table[i];
while(ptr!=NULL)
{
node* predptr=ptr;
ptr=ptr->next;
free(predptr);
}
}
}
return true;
}