/* This program classifies movies as hits or flops using the nearest neighbor algorithm. The program begins by prompting the user to provide the name of the file containing the sample set (set of already classified films). For each film, the data are: the percentage of hits of the director and the percentage of hits of the leading members of the cast. The program then reads the data of at most MAX_NO_FILMS classified films. Next the program prompts the user for data concerning unclassified films. The program finds the film nearest the unknown sample (by comparing the squares of Euclidean distances between the unclassified film and the classified films). The program assigns the unknown film the class of the film nearest it. The user terminates the program by generating EOF. */ #include #include #include #define MAX_NO_FILMS 100 /* maximum number of classified films */ #define HIT 1 main() { int numb_films = 0; /* number of films in sample set */ int i; int nearest; /* index of nearest film */ int eof_flag; double sdist; /* square of distance */ double min_dist; /* minimum distance */ FILE *fp; char file_name[ FILENAME_MAX ]; /* name of file containing sample set */ struct hit_flop { double dir_hits; /* percentage of hits of the director */ double cast_hits; /* percentage of hits of the leading members of the cast */ int code; /* 1 if a hit; 0 if a flop */ }; struct hit_flop film[ MAX_NO_FILMS ]; double unknown_dir_hits; /* percentage of hits of the director of a film to be classified */ double unknown_cast_hits; /* percentage of hits of the leading members of the cast of a film to be classified */ printf( "Enter name of file containing the sample set:\n" ); scanf( "%s", file_name ); fp = fopen( file_name, "r" ); /* read sample file */ while ( numb_films < MAX_NO_FILMS && fscanf( fp, "%lf", &film[ numb_films ].dir_hits) != EOF ) { fscanf( fp, "%lf", &film[ numb_films ].cast_hits ); fscanf( fp, "%d", &film[ numb_films ].code ); numb_films++; } /* input values for unknown films and classify each using the nearest neighbor algorithm */ do { printf( "\n\nEnter the percentage of hits of the\n" "director of the film to be classified or\n" "generate EOF to terminate the program: " ); if ( ( eof_flag = scanf( "%lf", &unknown_dir_hits ) ) != EOF ) { printf( "\n\nEnter the percentage of hits of the\n" "leading members of the cast of the film\n" "to be classified: "); scanf( "%lf", &unknown_cast_hits ); /* find the film nearest the unknown */ min_dist = DBL_MAX; for ( i = 0; i < numb_films; i++ ) { sdist = ( unknown_dir_hits - film[ i ].dir_hits ) * ( unknown_dir_hits - film[ i ].dir_hits ) + ( unknown_cast_hits - film[ i ].cast_hits ) * ( unknown_cast_hits - film[ i ].cast_hits ); if ( sdist < min_dist ) { min_dist = sdist; nearest = i; } } printf( "\n\nThe film is a "); if ( film[ nearest ].code == HIT ) printf( "HIT!\n" ); else printf( "flop.\n" ); } } while ( eof_flag != EOF ); return EXIT_SUCCESS; }