Skip to content

Instantly share code, notes, and snippets.

/dictionary.c Secret

Created January 10, 2017 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1a3e637eb5d40565ee91ab157759edda to your computer and use it in GitHub Desktop.
Save anonymous/1a3e637eb5d40565ee91ab157759edda to your computer and use it in GitHub Desktop.
CS50-pset5 dictionary.c
/**
* Implements a dictionary's functionality.
*/
#include <stdbool.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include "dictionary.h"
// Root Node
node *root = NULL;
// Tracks No. of words in dictionary
int words = 0;
node *createnode(void)
{
// allocate memory for new node
node* new_node = (node*) malloc(sizeof(node));
new_node->is_word = false;
// set all pointers to NULL
for (int i = 0; i < 27; i++)
new_node->children[i] = NULL;
return new_node;
}
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char *word)
{
node *trav = root;
int c;
int i = 0;
do
{
// Reads characters of words one by one
c = word[i];
// change to lowercase
if(c <= 90 && c >= 65)
{
c += 32;
}
// Only allows alphabets or apostrophe
if((c >= 97 && c <= 122) || (c == '\''))
{
if(trav->children[c - 96] == NULL)
{
return false;
}
else
{
trav = trav->children[c - 96];
}
}
i++;
}while(c != '\0');
return trav->is_word;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char *dictionary)
{
// open input file
FILE *dict = fopen(dictionary, "r");
if(dict == NULL)
{
printf("File doesn't exist.\n");
return false;
}
char c;
// memory aloocation to root node
root = createnode();
// Node trav to tranverse through the linked list
node *trav = root;
do
{
c = fgetc(dict);
if(isalpha(c) || c == '\'')
{
// Checks if the node already exists or not
if(trav->children[c-96] == NULL)
{
trav->children[c-96] = createnode();
}
trav = trav->children[c-96];
}
else if(c == '\n')
{
// Sets is_word to true when we reach end of the word
trav->is_word = true;
words++;
trav = root;
}
}while(c != EOF);
fclose(dict);
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
return words;
}
bool delnode(node *trav)
{
// calls function delnode on every node in node's children
for(int i = 0; i < 27; i++)
{
if(trav->children[i] != NULL)
{
return delnode(trav->children[i]);
}
}
free(trav);
return true;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
// calls recursive function delnode
return delnode(root);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment