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 <stdbool.h>
- #include <ctype.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include "dictionary.h"
- #include <string.h>
- typedef struct node
- {
- bool isword;
- struct node* children[27];
- }node;
- unsigned int dSize = 0; // keeps track of the size of the dictionary
- node* head; // makes sure I can still use this node that way I can unload
- /**
- * Returns true if word is in dictionary else false.
- */
- bool check(const char* word)
- {
- node* spider = head; // traversing the node
- int charVal = -1;
- if(word == NULL)
- {
- return false;
- }
- for(int i = 0; i < strlen(word);i++)
- {
- charVal = (tolower(word[i])-97);
- if(charVal == 39)
- {
- charVal = 26;
- }
- if(spider ->children[charVal] != NULL)
- {
- spider = spider -> children[charVal];
- if(i == strlen(word)-1)
- {
- if(spider ->isword == true)
- {
- return true;
- }
- }
- }
- else return false;
- }
- return false;
- }
- /**
- * Loads dictionary into memory. Returns true if successful else false.
- */
- bool load(const char* dictionary)
- {
- head = malloc(sizeof(node));
- node* spider = head; // traversing the node
- FILE *dict = fopen(dictionary,"r");
- char word[LENGTH + 1]= {}; //for reading the words in the dictionary
- int charVal = 0;
- int app = 0;
- if (dict == NULL)
- {
- return false;
- }
- while(fscanf(dict, "%s\n", word) != EOF) // word is captured
- {
- spider = head;
- app = 0;
- for(int i = 0; i < strlen(word)+app;i++)
- {
- charVal = (tolower(word[i])-97);
- if(charVal == 39)
- {
- app = 1;
- charVal = 26;
- }
- if(spider -> children[charVal] == NULL)
- {
- spider -> children[charVal] = malloc(sizeof(node));
- spider = spider -> children[charVal];
- if(i == strlen(word)-1)
- {
- dSize++;
- spider ->isword = true;
- }
- }
- else
- {
- spider = spider -> children[charVal];
- }
- }
- }
- fclose(dict);
- return true;
- }
- /**
- * Returns number of words in dictionary if loaded else 0 if not yet loaded.
- */
- unsigned int size(void)
- {
- return dSize;
- }
- /*
- * Unloads dictionary from memory. Returns true if successful else false.
- */
- bool freeStuff(node* spider) //recursive function to free
- {
- for(int i = 0; i < 27; i++)
- {
- if(spider -> children[i] != NULL)
- {
- freeStuff(spider -> children[i]);
- }
- }
- free(spider);
- return true;
- }
- bool unload(void)
- {
- return freeStuff(head);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement