Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implements a dictionary's functionality
- #include <ctype.h>
- #include <stdbool.h>
- #include <stdio.h>
- #include "dictionary.h"
- #include <cs50.h>
- #include <string.h>
- #include <stdlib.h>
- #include <strings.h>
- // Represents a node in a hash table
- typedef struct node
- {
- char word[LENGTH + 1];
- struct node *next;
- } node;
- // TODO: Choose number of buckets in hash table
- const unsigned int N = 26;
- // Hash table
- node *table[N];
- int wordcount = 0;
- // Returns true if word is in dictionary, else false
- bool check(const char *word)
- {
- int index = hash(word);
- node *ptr = table[index];
- while (ptr != NULL)
- {
- if (strcasecmp(ptr->word,word) == 0)
- {
- return true;
- }
- ptr=ptr->next;
- }
- return false;
- }
- // Hashes word to a number
- unsigned int hash(const char *word)
- {
- // TODO: Improve this hash function
- return toupper(word[0]) - 'A';
- }
- // Loads dictionary into memory, returning true if successful, else false
- bool load(const char *dictionary)
- {
- // Open the dictionary file
- FILE *source = fopen(dictionary, "r");
- if (source != NULL)
- {
- // Read each word in the file
- char str[LENGTH+1];
- while(fscanf(source, "%s", str)==1)
- {
- // Add each word to the hash table
- node *n = malloc(sizeof(node));
- if (n==NULL)
- {
- return 1;
- }
- strcpy(n->word, str);
- int index = hash(str);
- if (table[index] == NULL)
- {
- n->next= NULL;
- }
- else
- {
- n->next = table[index];
- }
- table[index] = n;
- wordcount +=1;
- }
- return true;
- }
- fclose(source);
- // Close the dictionary file
- return true;
- }
- // Returns number of words in dictionary if loaded, else 0 if not yet loaded
- unsigned int size(void)
- {
- return wordcount;
- }
- // Unloads dictionary from memory, returning true if successful, else false
- bool unload(void)
- {
- for (int i = 0; i < N; i++)
- {
- node *pointer = table[i];
- while (pointer != NULL)
- {
- node *tmp = pointer;
- pointer = pointer->next;
- free(tmp);
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement