Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Implements a dictionary's functionality.
- */
- #include <stdbool.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include "dictionary.h"
- // own functions and variables
- int counter = 0;
- // amount of children for the node
- #define amount_children 27
- // Struct for the node
- typedef struct node
- {
- bool is_word;
- struct node* children[amount_children];
- }
- node;
- // root declared as a global variabel
- node* root = NULL;
- // function for unloading using recursion
- bool uload(node*ptr);
- /**
- * Returns true if word is in dictionary else false.
- */
- bool check(const char *word)
- {
- node * ptr = root;
- for (int i=0; i<=strlen(word); i++)
- {
- if (word[i]=='\0' && ptr->is_word==true)
- return true;
- if (islower(word[i]))
- {
- if (ptr->children[word[i]-'a'+1] == NULL)
- return false;
- ptr = ptr->children[word[i]-'a'+1];
- }
- if (isupper(word[i]))
- {
- if (ptr->children[word[i]-'A'+1] == NULL)
- return false;
- ptr = ptr->children[word[i]-'A'+1];
- }
- if (word[i]=='a'-1)
- {
- if (ptr->children[0] == NULL)
- return false;
- ptr = ptr->children[word[i]-'a'+1];
- }
- /*
- if (islower(word[i]) && ptr->children[word[i]-'a'+1] == NULL)
- return false;
- if (isupper(word[i]) && ptr->children[word[i]-'B'] == NULL)
- return false;
- if (word[i]=='a'-1 && ptr->children[word[i]-'a'+1] == NULL)
- return false;
- if (islower(word[i]))
- ptr = ptr->children[word[i]-'a'+1];
- if (isupper(word[i]))
- ptr = ptr->children[word[i]-'a'+1];
- if (word[i]=='a'-1)
- ptr = ptr->children[word[i]-'a'+1];
- */
- }
- return false;
- }
- /**
- * Loads dictionary into memory. Returns true if successful else false.
- */
- bool load(const char *dictionary)
- {
- FILE* input = fopen(dictionary, "r");
- if (input==NULL)
- return false;
- char word[LENGTH+1];
- root = calloc(1, sizeof(node));
- root->is_word=false;
- int n = 0;
- while (true)
- {
- memset(word, '\0', sizeof(word));
- fscanf(input, "%s", word);
- if (word[0]=='\0')
- return true;
- node *ptr = root;
- for (int i=0; i<=strlen(word); i++)
- {
- if (word[i]=='\0')
- {
- ptr->is_word = true;
- break;
- }
- n = word[i]-'a'+1;
- if (ptr->children[n]==NULL)
- {
- ptr->children[n] = calloc(1, sizeof(node));
- }
- ptr = ptr->children[n];
- }
- counter++;
- }
- }
- /**
- * Returns number of words in dictionary if loaded else 0 if not yet loaded.
- */
- unsigned int size(void)
- {
- if (counter>0)
- return counter;
- else
- return 0;
- }
- /**
- * Unloads dictionary from memory. Returns true if successful else false.
- */
- bool unload(void)
- {
- return uload(root);
- }
- bool uload(struct node *ptr)
- {
- for (int i = 0; i < amount_children; i++)
- {
- if(ptr->children[i]!=NULL)
- uload(ptr->children[i]);
- }
- free(ptr);
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement