/* DataSet.c Implementation of a DataSet Class [Taken from requirements .....] Author: J Morris Date Last Modified: 17 October, 1997 */ #include #include #include "Boolean.h" struct dataset { int max_items; int cnt; double *data; }; #include "DataSet.h" DataSet ConsDataSet( int max_items ) { /* Construct a new data set - max_items is the maximum number of points in the data set Pre-cond: max_items > 0 Post-cond: returns a newly constructed DataSet or NULL if insufficient memory */ DataSet ds; assert( max_items > 0 ); ds = malloc( sizeof( struct dataset ) ); if ( ds != NULL ) { ds->max_items = max_items; ds->cnt = 0; ds->data = malloc( max_items*sizeof( double ) ); if ( ds->data == NULL ) { free( ds ); ds = NULL; } } return NULL; } int DeleteDataSet( DataSet ds ) { /* Delete a data set. Pre-cond: ds is a valid DataSet Post-cond: space used by ds has been freed returns TRUE if no errors, FALSE on error */ assert( ds != NULL ); assert( ds->data != NULL ); free( ds->data ); free( ds ); return TRUE; } int ClearDataSet( DataSet ds ) { /* Reset the DataSet ds (allows the same space to be re-used, without free/malloc overhead) Pre-cond: ds is a valid DataSet Post-cond: entries in ds have all been cleared, */ assert( ds != NULL ); assert( ds->data != NULL ); ds->cnt = 0; return TRUE; } int TotalPoints( DataSet ds ) { /* Count total points in the data set Pre-cond: ds is a valid DataSet Post-cond: returns count of points added to the DataSet */ assert( ds != NULL ); return ds->cnt; } int AddDatum( DataSet ds, double x ) { assert( ds != NULL ); if ( ds->cnt >= ds->max_items ) return FALSE; ds->data[ds->cnt] = x; ds->cnt++; return TRUE; } double Maximum( DataSet ds, int *index ) { int j, k; double max; assert( ds != NULL ); if ( ds->cnt == 0 ) { *index = -1; return 0.0; } max = ds->data[0]; k = 0; for(j=1; jcnt; j++ ) { if ( ds->data[j] > max ) { max = ds->data[j]; k = j; } } *index = k; return max; } double Minimum( DataSet ds, int *index ) { int j, k; double min; assert( ds != NULL ); if ( ds->cnt == 0 ) { *index = -1; return 0.0; } min = ds->data[0]; k = 0; for(j=1; jcnt; j++ ) { if ( ds->data[j] < min ) { min = ds->data[j]; k = j; } } *index = k; return min; } double SampleMean( DataSet ds, int *num_below ) { int k, cnt; double sum, mean; assert( ds != NULL ); assert( num_below != NULL ); if ( ds->cnt == 0 ) { *num_below = 0; return 0.0; } sum = 0.0; for(k=0;kcnt;k++) { sum = sum + ds->data[k]; } mean = sum / ds->cnt; cnt = 0; for( k=0;kcnt;k++) { if ( ds->data[k] < mean ) cnt++; } *num_below = cnt; return mean; }