Created
July 3, 2016 04:50
-
-
Save Anirudh257/8aef306cfb7c9239ef1b5052933f20df to your computer and use it in GitHub Desktop.
PSet 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* dictionary.c | |
* | |
* Computer Science 50 | |
* Problem Set 5 | |
* | |
* Implements a dictionary's functionality. | |
*/ | |
#include <stdbool.h> | |
#include<stdio.h> | |
#include<stdlib.h> | |
#include<ctype.h> | |
#include<string.h> | |
#include "dictionary.h" | |
//To store the number of words in the dictionary | |
static int count = 0; | |
// Definition of a word | |
typedef struct Node | |
{ | |
char word[LENGTH + 1]; | |
struct Node *next; | |
} | |
node; | |
node *head; | |
node *hashtable[500]; | |
//Function for hashing | |
int hash_func(char *word) | |
{ | |
return (tolower(word[0]) - 'a'); | |
} | |
/** | |
* Returns true if word is in dictionary else false. | |
*/ | |
bool check(const char* word) | |
{ | |
for(int i = 0,j = 0,n = strlen(word);i < n;i++,j++) | |
{ | |
//Checking for only alphabets and apostrophes | |
if(isalpha(word[i]) || word[i] == '\"') | |
{ | |
if(strcmp(hashtable[j]->word, word)==0) | |
{ | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
/** | |
* Loads dictionary into memory. Returns true if successful else false. | |
*/ | |
bool load(const char* dictionary) | |
{ | |
FILE * dic = fopen(dictionary,"r"); | |
if(dic == NULL) | |
{ | |
printf("File not found\n"); | |
return false; | |
} | |
//Check if we have reached the end of file | |
if(!feof(dic)) | |
{ | |
node* new_node = malloc(sizeof(node)); | |
fscanf(dic,"%s",new_node->word); | |
int index = hash_func(new_node->word); | |
//Check if the index returned is free | |
if(hashtable[index] == NULL) | |
{ | |
hashtable[index] = new_node; | |
new_node->next = NULL; | |
} | |
//If location is not vacant, traverse the remaining hashtable to find a vacant location to store the word | |
else | |
{ | |
node* trav = hashtable[index]; | |
while(trav != NULL) | |
{ | |
trav = trav->next; | |
} | |
trav = new_node; | |
} | |
count++; | |
} | |
fclose(dic); | |
return true; | |
} | |
/** | |
* Returns number of words in dictionary if loaded else 0 if not yet loaded. | |
*/ | |
unsigned int size(void) | |
{ | |
return count; | |
} | |
/** | |
* Unloads dictionary from memory. Returns true if successful else false. | |
*/ | |
bool unload(void) | |
{ | |
node* trav = head; | |
while(trav != NULL) | |
{ | |
node* temp = trav; | |
trav = trav->next; | |
free(temp); | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment