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 <string.h>
- #include <strings.h>
- #include <stdio.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;
- // TODO: Choose number of buckets in hash table
- const unsigned int N = 26;
- // Hash table
- node *table[N];
- int size_check = 0;
- // Returns true if word is in dictionary, else false
- bool check(const char *word)
- {
- // TODO
- int index = hash(word);
- node *cursor = table[index];
- while (cursor != NULL)
- {
- if (strcasecmp(cursor->word, word) == 0)
- {
- return true;
- }
- cursor = cursor->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)
- {
- // TODO
- FILE *file = fopen(dictionary, "r");
- if (file == NULL)
- {
- return false;
- }
- char word[LENGTH + 1];
- while (fscanf(file, "%s", word) != EOF)
- {
- node *temp = malloc(sizeof(node));
- if (temp == NULL)
- {
- unload();
- return false;
- }
- strcpy(temp->word, word);
- temp->next = NULL;
- size_check++;
- int index = hash(temp->word);
- node *head = malloc(sizeof(node));
- if (table[index] == NULL)
- {
- head = temp;
- table[index] = head;
- }
- else
- {
- temp->next = head;
- head = temp;
- }
- }
- fclose(file);
- return true;
- }
- // Returns number of words in dictionary if loaded, else 0 if not yet loaded
- unsigned int size(void)
- {
- // TODO
- return size_check;
- }
- // Unloads dictionary from memory, returning true if successful, else false
- bool unload(void)
- {
- // TODO
- for (int i = 0; i < N; i++) // Check all "buckets"
- {
- node *cursor = table[i];
- while (cursor != NULL) // Check the list until end
- {
- node *tmp = table[i];
- cursor = cursor->next;
- free(tmp);
- tmp = cursor;
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment