I have here a program created for pset5 of the CS50 course. The program compiles correctly and does as it should. However, is there any way to improve the run time of this program? Are there any pieces of code that are redundant and can be omitted? And is there anything that can be improved on in general?
/*
* Implements a dictionary's functionality.
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "dictionary.h"
typedef struct trie
{
bool word;
struct trie* children[27];
}trie;
trie* root;
unsigned int wordCount;
// Function that frees a node from the heap.
void freenode(trie* node)
{
for (int i = 0; i < 27; i++)
{
if (node->children[i] != NULL)
{
freenode(node->children[i]);
}
}
free(node);
}
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char* word)
{
int n = strlen(word);
trie* node = root;
for (int i=0; i < n; i++)
{
char c = tolower(word[i]);
if (c == '\'')
{
// ASCII a (97) + 26
c = 123;
}
struct trie* current = node->children[c-97];
if (current == NULL)
{
return false;
}
else
{
node = current;
}
}
if (node->word == true)
{
return true;
}
return false;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char* dictionary)
{
// Open the dictionary file
FILE* d = fopen(dictionary, "r");
if (d == NULL)
{
return false;
}
root = calloc(1, sizeof(trie));
trie* node = root;
for (char c = tolower(fgetc(d)); c != EOF; c = fgetc(d))
{
if (c == '\n')
{
if (node != root)
{
wordCount++;
node->word = true;
node = root;
}
}
else
{
if (c == '\'')
{
c = 123;
}
struct trie* current = node->children[c-97];
if (current == NULL)
{
node->children[c-97] = calloc(1, sizeof(trie));
node = node->children[c-97];
}
else
{
node = current;
}
}
}
fclose(d);
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
return wordCount;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
freenode(root);
return true;
}