Me@0: /* Me@0: * Copyright 2010 OpenSourceStewardshipFoundation.org Me@0: * Licensed under GNU General Public License version 2 Me@0: * Me@0: * Author: seanhalle@yahoo.com Me@0: * Me@0: */ Me@0: Me@0: #include "Histogram.h" Me@0: #include Me@0: Me@0: Me@0: /*This Histogram Abstract Data Type has a number of bins plus a range of Me@0: * values that the bins span, both chosen at creation. Me@0: * Me@0: *One creates a Histogram instance using the makeHistogram function, then Me@0: * updates it with the addToHist function, and prints it out with the Me@0: * printHist function. Me@0: * Me@0: *Note, the bin width is an integer, so the end of the range is adjusted Me@0: * accordingly. Use the bin-width to calculate the bin boundaries. Me@0: */ Me@0: Me@0: Me@0: Histogram * Me@0: makeHistogram( int numBins, int startOfRange, int endOfRange ) Me@0: { Me@0: Histogram *hist; Me@0: int i; Me@0: Me@0: hist = malloc( sizeof(Histogram) ); Me@0: hist->bins = malloc( numBins * sizeof(int) ); Me@0: Me@0: hist->numBins = numBins; Me@0: hist->binWidth = (endOfRange - startOfRange) / numBins; Me@0: hist->endOfRange = startOfRange + hist->binWidth * numBins; Me@0: hist->startOfRange = startOfRange; Me@0: Me@0: for( i = 0; i < hist->numBins; i++ ) Me@0: { Me@0: hist->bins[ i ] = 0; Me@0: } Me@0: Me@0: return hist; Me@0: } Me@0: Me@0: void Me@0: addToHist( int value, Histogram *hist ) Me@0: { Me@0: int binIdx; Me@0: Me@0: if( value < hist->startOfRange ) Me@0: { binIdx = 0; Me@0: } Me@0: else if( value > hist->endOfRange ) Me@0: { binIdx = hist->numBins - 1; Me@0: } Me@0: else Me@0: { Me@0: binIdx = (value - hist->startOfRange) / hist->binWidth; Me@0: } Me@0: Me@0: hist->bins[ binIdx ] += 1; Me@0: } Me@0: Me@0: void Me@0: printHist( Histogram *hist ) Me@0: { Me@0: int binIdx, i, numBars, maxHeight, barValue, binStart, binEnd; Me@0: Me@0: maxHeight = 0; Me@0: for( i = 0; i < hist->numBins; i++ ) Me@0: { Me@0: if( maxHeight < hist->bins[ i ] ) maxHeight = hist->bins[ i ]; Me@0: } Me@0: barValue = maxHeight / 60; //60 spaces across page for tallest bin Me@0: Me@0: printf("histogram: \n"); Me@0: if( barValue == 0 ) printf("error printing histogram\n"); Me@0: for( binIdx = 0; binIdx < hist->numBins; binIdx++ ) Me@0: { Me@0: binStart = hist->startOfRange + hist->binWidth * binIdx; Me@0: binEnd = binStart + hist->binWidth - 1; Me@0: printf("bin range: %d - %d", binStart, binEnd ); Me@0: Me@0: numBars = hist->bins[ binIdx ] / barValue; Me@0: //print one bin, height of bar is num dashes across page Me@0: for( i = 0; i < numBars; i++ ) Me@0: { Me@0: printf("-"); Me@0: } Me@0: printf("\n"); Me@0: } Me@0: } Me@0: