/*********************************************** dictionary.c Started by Jeff Ondich on 5/8/97 Last modified 5/9/97 Implementation for a simple dictionary data type. ***********************************************/ #include #include #include #include "dictionary.h" /*************************************************** InitializeDictionary returns TRUE if d is non-NULL and initialization is successful, FALSE otherwise. ***************************************************/ boolean InitializeDictionary( Dictionary *d ) { if( d != NULL ) { d->nWords = 0; d->entry = (Word *)malloc( sizeof(Word) * MAX_WORDS ); if( d->entry == NULL ) return( FALSE ); return( TRUE ); } else return( FALSE ); } /*************************************************** AddToDictionary returns FALSE if d or newWord is NULL, if the dictionary is already full, or if adding to the dictionary fails. Otherwise, AddToDictionary adds newWord to the dictionary and returns TRUE. ***************************************************/ boolean AddToDictionary( Dictionary *d, char *newWord ) { int i; if( d == NULL || newWord == NULL || d->nWords >= MAX_WORDS ) return( FALSE ); /* Shift words down to make space for the new word. */ for( i=d->nWords-1; i >= 0 && strcmp( newWord, d->entry[i] ) < 0; i-- ) strcpy( d->entry[i+1], d->entry[i] ); /* Put the new word in its place. Prevent the new word from overflowing its array by using strncpy(). */ strncpy( d->entry[i+1], newWord, MAX_WORD_LENGTH ); d->entry[i+1][MAX_WORD_LENGTH-1] = '\0'; /* Update word count. */ (d->nWords)++; return( TRUE ); } /*************************************************** IsInDictionary returns TRUE if d and searchWord are non-NULL and searchWord is in the dictionary. Otherwise, IsInDictionary returns FALSE. This implementation of IsInDictionary uses a binary search on a sorted array of strings. ***************************************************/ boolean IsInDictionary( Dictionary *d, char *searchWord ) { int left, right, middle, comparison; if( d == NULL ) return( FALSE ); left = 0; right = d->nWords - 1; while( left <= right ) { middle = (right + left) / 2; comparison = strcmp( searchWord, d->entry[middle] ); if( comparison == 0 ) return( TRUE ); else if( comparison > 0 ) left = middle + 1; else right = middle - 1; } return( FALSE ); } /*************************************************** PrintDictionary prints out the dictionary in whatever form is appropriate for debugging. ***************************************************/ void PrintDictionary( FILE *f, Dictionary *d ) { int i; if( d != NULL && f != NULL ) { fprintf( f, "\nDictionary:\n" ); for( i=0; i < d->nWords; i++ ) fprintf( f, "\t%s\n", d->entry[i] ); fprintf( f, "End of Dictionary.\n\n" ); } }