CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

The word with the highest value

Can we find which valid word from a dictionary has the highest value?


#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>

#define DICTIONARY      "/usr/share/dict/words"
#define LONGEST_WORD    100

//  FIND THE WORD WITH THE BEST VALUE
void findbest( char filename[] )
{
    FILE        *fp  = fopen(filename, "r");

//  ENSURE THAT WE CAN OPEN (WITH READ-ACCESS) THE FILE
    if(fp != NULL) {
        char    bestword[LONGEST_WORD];
        int     bestvalue       = 0;
        char    thisword[LONGEST_WORD];
        int     thisvalue       = 0;

//  READ EACH LINE OF THE FILE
        while( fgets(thisword, sizeof thisword, fp) != NULL ) {
//  REPLACE THE NEWLINE CHARACTER WITH A NULL-BYTE
            trim_line( thisword );

//  ENSURE THAT THIS WORD IS VALID (previously defined)
            if( valid_word(thisword) ) {
                thisvalue = calc_value( thisword );

//  IS THIS WORD BETTER THAN THE PREVIOUSLY BEST?
                if(bestvalue < thisvalue) {
                    bestvalue   = thisvalue;    // save current details
                    strcpy(bestword, thisword);
                }
            }
        }
        fclose(fp);
        printf("best word is %s = %i\n", bestword, bestvalue);
    }
}

int main(int argc, char *argv[])
{
    findbest( DICTIONARY );
    return 0;
}


Full solution here.

 


CITS2002 Systems Programming, Lecture 8, p11, 17th August 2021.