Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * dictionary.c
- *
- * Computer Science 50
- * Problem Set 5
- *
- * Implements a dictionary's functionality.
- */
- #include <ctype.h>
- #include <stdbool.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include "dictionary.h"
- node* root;
- unsigned int words_loaded = 0;
- /**
- * Returns true if word is in dictionary else false.
- */
- bool check(const char* word)
- {
- // ptr to traverse trie starting from root
- node* ptr = root;
- int i = 0;
- int letter;
- // loops through input word
- while (true)
- {
- letter = (int) *(word + i);
- if (isupper(word[i]))
- {
- if (ptr->children[letter - 'A'] == NULL)
- {
- return false;
- }
- else if (word[i + 1] == '\0')
- {
- if (ptr->is_word == true)
- {
- return true;
- }
- return false;
- }
- }
- else if (islower(word[i]))
- {
- if (ptr->children[letter - 'a'] == NULL)
- {
- return false;
- }
- else if (word[i + 1] == '\0')
- {
- if (ptr->is_word == true)
- {
- return true;
- }
- return false;
- }
- }
- else if (word[i] == '\'')
- {
- if (ptr->children[26] == NULL)
- {
- return false;
- }
- else if (word[i + 1] == '\0')
- {
- if (ptr->is_word == true)
- {
- return true;
- }
- return false;
- }
- }
- i++;
- }
- }
- /**
- * Loads dictionary into memory. Returns true if successful else false.
- */
- bool load(const char* dictionary)
- {
- FILE* dict = fopen(dictionary, "r");
- if (dict == NULL)
- {
- printf("Dictionary could not be opened.\n");
- return false;
- }
- root = calloc(1, sizeof(node));
- node* ptr = root;
- for (int c = fgetc(dict); c != EOF; c = fgetc(dict))
- {
- if (isalpha(c))
- {
- if (ptr->children[c - 'a'] == NULL)
- {
- ptr->children[c - 'a'] = calloc(1, sizeof(node));
- ptr = ptr->children[c - 'a'];
- }
- else
- {
- ptr = ptr->children[c - 'a'];
- }
- }
- else if (c == '\'')
- {
- if (ptr->children[26] == NULL)
- {
- ptr->children[26] = calloc(1, sizeof(node));
- ptr = ptr->children[26];
- }
- else
- {
- ptr = ptr->children[26];
- }
- }
- // must be new-line
- else
- {
- ptr->is_word = true;
- ptr = root;
- words_loaded++;
- }
- }
- return true;
- }
- /**
- * Returns number of words in dictionary if loaded else 0 if not yet loaded.
- */
- unsigned int size(void)
- {
- return words_loaded;
- }
- void unloader(node* track)
- {
- node* ptr = track;
- int i = 0;
- while (i != 26)
- {
- if (ptr->children[i] != NULL)
- {
- unloader(ptr->children[i]);
- }
- i++;
- }
- node* temp = ptr;
- free(temp);
- }
- /**
- * Unloads dictionary from memory. Returns true if successful else false.
- */
- bool unload(void)
- {
- unloader(root);
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement