Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implements a dictionary's functionality
- #include <stdio.h>
- #include <stdbool.h>
- #include <string.h>
- #include <strings.h>
- #include <stdlib.h>
- #include "dictionary.h"
- // Represents a node in a hash table
- typedef struct node
- {
- char word[LENGTH + 1];
- struct node *next;
- }
- node;
- // Number of buckets in hash table
- const unsigned int N = 50000;
- int count=0;
- // Hash table
- node *table[N];
- void free_linkedlist(node *cursor);
- // Returns true if word is in dictionary else false
- bool check(const char *word)
- {
- node *head=table[hash(word)];
- node *cursor=head;
- while(cursor != NULL)
- {
- if(strcasecmp(cursor->word,word)==1){
- return true;
- }
- else
- {
- cursor=cursor->next;
- }
- }
- return false;
- }
- // Hashes word to a number
- size_t precision=2;
- unsigned int hash(const char *word)
- {
- return ((*(size_t*)word)>>precision) % N;
- }
- // Loads dictionary into memory, returning true if successful else false
- bool load(const char *dictionary)
- {
- // open dictionary file
- FILE* dicfile = fopen(dictionary,"r");
- if(dicfile==NULL){
- printf("couldnt open dictionary file\n");
- return false;
- }
- char word[LENGTH+1]={'\0'};
- //read strings from file till EOF.
- while(fscanf(dicfile,"%s",word)==1)
- {
- node* new_node=malloc(sizeof(node));
- if(new_node== NULL){
- unload();
- return false;
- }
- //copy word into node structure
- strcpy(new_node->word,word);
- int key=hash(new_node->word);
- if(!table[key]){
- table[key]=new_node;
- count++;
- }
- else
- {
- new_node->next=table[key];
- table[key]=new_node;
- count++;
- }
- }
- return true;
- }
- // Returns number of words in dictionary if loaded else 0 if not yet loaded
- unsigned int size(void)
- {
- // TODO
- return count;
- }
- // Unloads dictionary from memory, returning true if successful else false
- bool unload(void)
- {
- for(int i=0; i<N; i++)
- {
- free_linkedlist(table[i]);
- }
- return true;
- }
- void free_linkedlist(node *cursor)
- {
- while(cursor != NULL)
- {
- node *temp=cursor;
- cursor=cursor->next;
- free(temp);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement