Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implements a dictionary's functionality
- #include <stdbool.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <strings.h>
- #include <cs50.h>
- #include "dictionary.h"
- // Represents a node in a hash table
- typedef struct node
- {
- char word[LENGTH + 1];
- struct node *next;
- }
- node;
- int number_of_words = 0;
- // Number of buckets in hash table
- const unsigned int N = 20000;
- // Hash table
- node *table[N];
- // Returns true if word is in dictionary else false
- bool check(const char *word)
- {
- int hash_num = hash(word);
- node *p = table[hash_num];
- while (p != NULL)
- {
- int a = strcasecmp(p->word, word);
- if (a == 0)
- {
- return true;
- }
- p = p->next;
- }
- return false;
- }
- // Hashes word to a number
- unsigned int hash(const char *word)
- {
- int sum = 0;
- while(*word != '\0')
- {
- if(*word >='A' && *word < 'A'+26)
- sum=sum+(*word -'A' + 1);
- else if(*word >='a' && *word < 'a'+26)
- sum=sum+(*word -'a' + 1);
- else
- return -1;
- word++;
- }
- return sum;
- }
- // Loads dictionary into memory, returning true if successful else false
- bool load(const char *dictionary)
- {
- // Openning the dictionary file for reading
- FILE *file = fopen(dictionary, "r");
- if ( fopen(dictionary, "r") == NULL)
- {
- return false;
- }
- string word = NULL;
- while (fscanf(file, "%s", word) != EOF)
- {
- node *n = malloc(sizeof(node));
- if (n == NULL)
- {
- return 1;
- return false;
- }
- n->next = NULL;
- strcpy(n->word, word);
- //Handling collision
- if (table[hash(word)] != NULL)
- {
- n->next = table[hash(word)];
- table[hash(word)] = n;
- }
- else
- {
- table[hash(word)] = n;
- }
- }
- return true;
- }
- // Returns number of words in dictionary if loaded else 0 if not yet loaded
- unsigned int size(void)
- {
- return number_of_words;
- }
- // Unloads dictionary from memory, returning true if successful else false
- bool unload(void)
- {
- node *cursor = malloc(sizeof(node));
- if (cursor == NULL)
- {
- return 1;
- return false;
- }
- node *tmp = malloc(sizeof(node));
- if (tmp == NULL)
- {
- return 1;
- return false;
- }
- int n = 0;
- while (table[n] != NULL)
- {
- cursor = table[n]->next;
- tmp = table[n];
- free(tmp);
- tmp = cursor;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement