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 <stdio.h>
- #include <string.h>
- #include <stdbool.h>
- #include <stdlib.h>
- #include "dictionary.h"
- int words = 0;
- struct node* root;
- /**
- * Returns true if word is in dictionary else false.
- */
- bool check(const char* word)
- {
- node* current = root;
- for(int i = 0; i< strlen(word); i++)
- {
- if (current->children[charNumber(word[i])]==NULL)
- {
- return false;
- }
- current = current->children[charNumber(word[i])];
- }
- if (current->is_word)
- {
- return true;
- }
- return false;
- }
- /**
- * Loads dictionary into memory. Returns true if successful else false.
- */
- bool load(const char* dictionary)
- {
- FILE *f = fopen(dictionary, "r");
- if (!f)
- {
- return false;
- }
- root = alloc_node();
- struct node* current = NULL;
- char holder[46];
- while (fgets(holder, 46, f))
- {
- if (feof(f))
- {
- break;
- }
- current = root;
- int a = strlen(holder);
- for (int i = 0; i< a; i++)
- {
- int index = tolower(holder[i]) - 'a';
- if (current->children[index]==NULL)
- {
- current->children[index] = alloc_node();
- }
- current = current->children[index];
- }
- current->is_word = true;
- words++;
- }
- fclose(f);
- return true;
- }
- /**
- * Returns number of words in dictionary if loaded else 0 if not yet loaded.
- */
- unsigned int size(void)
- {
- return words;
- }
- /**
- * Unloads dictionary from memory. Returns true if successful else false.
- */
- bool unload(void)
- {
- node* current = root;
- for (int i=0;i<27;i++)
- {
- if (current->children[i] != NULL)
- {
- free_node(current->children[i]);
- }
- }
- return true;
- }
- void free_node(node *val)
- {
- for (int i = 0; i < 27; i++)
- {
- if (val->children[i] != NULL)
- {
- free_node(val->children[i]);
- }
- }
- free(val);
- }
- node* alloc_node(void)
- {
- node *val = malloc(sizeof(node));
- for (int i = 0; i < 27; i++)
- {
- val->children[i] = NULL;
- }
- val->is_word = false;
- return val;
- }
- int charNumber(char c)
- {
- int num;
- if (c == '\'')
- {
- return 26;
- }
- else if(c >= 'A' && c <= 'Z')
- {
- c += 32;
- }
- num = c - 'a';
- return num;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement