annotate Histogram.c @ 0:6e864a0cb520

Initial add
author Me
date Sat, 11 Sep 2010 04:41:55 -0700
parents
children 3d35477a5121 13b8591dd045
rev   line source
Me@0 1 /*
Me@0 2 * Copyright 2010 OpenSourceStewardshipFoundation.org
Me@0 3 * Licensed under GNU General Public License version 2
Me@0 4 *
Me@0 5 * Author: seanhalle@yahoo.com
Me@0 6 *
Me@0 7 */
Me@0 8
Me@0 9 #include "Histogram.h"
Me@0 10 #include <malloc.h>
Me@0 11
Me@0 12
Me@0 13 /*This Histogram Abstract Data Type has a number of bins plus a range of
Me@0 14 * values that the bins span, both chosen at creation.
Me@0 15 *
Me@0 16 *One creates a Histogram instance using the makeHistogram function, then
Me@0 17 * updates it with the addToHist function, and prints it out with the
Me@0 18 * printHist function.
Me@0 19 *
Me@0 20 *Note, the bin width is an integer, so the end of the range is adjusted
Me@0 21 * accordingly. Use the bin-width to calculate the bin boundaries.
Me@0 22 */
Me@0 23
Me@0 24
Me@0 25 Histogram *
Me@0 26 makeHistogram( int numBins, int startOfRange, int endOfRange )
Me@0 27 {
Me@0 28 Histogram *hist;
Me@0 29 int i;
Me@0 30
Me@0 31 hist = malloc( sizeof(Histogram) );
Me@0 32 hist->bins = malloc( numBins * sizeof(int) );
Me@0 33
Me@0 34 hist->numBins = numBins;
Me@0 35 hist->binWidth = (endOfRange - startOfRange) / numBins;
Me@0 36 hist->endOfRange = startOfRange + hist->binWidth * numBins;
Me@0 37 hist->startOfRange = startOfRange;
Me@0 38
Me@0 39 for( i = 0; i < hist->numBins; i++ )
Me@0 40 {
Me@0 41 hist->bins[ i ] = 0;
Me@0 42 }
Me@0 43
Me@0 44 return hist;
Me@0 45 }
Me@0 46
Me@0 47 void
Me@0 48 addToHist( int value, Histogram *hist )
Me@0 49 {
Me@0 50 int binIdx;
Me@0 51
Me@0 52 if( value < hist->startOfRange )
Me@0 53 { binIdx = 0;
Me@0 54 }
Me@0 55 else if( value > hist->endOfRange )
Me@0 56 { binIdx = hist->numBins - 1;
Me@0 57 }
Me@0 58 else
Me@0 59 {
Me@0 60 binIdx = (value - hist->startOfRange) / hist->binWidth;
Me@0 61 }
Me@0 62
Me@0 63 hist->bins[ binIdx ] += 1;
Me@0 64 }
Me@0 65
Me@0 66 void
Me@0 67 printHist( Histogram *hist )
Me@0 68 {
Me@0 69 int binIdx, i, numBars, maxHeight, barValue, binStart, binEnd;
Me@0 70
Me@0 71 maxHeight = 0;
Me@0 72 for( i = 0; i < hist->numBins; i++ )
Me@0 73 {
Me@0 74 if( maxHeight < hist->bins[ i ] ) maxHeight = hist->bins[ i ];
Me@0 75 }
Me@0 76 barValue = maxHeight / 60; //60 spaces across page for tallest bin
Me@0 77
Me@0 78 printf("histogram: \n");
Me@0 79 if( barValue == 0 ) printf("error printing histogram\n");
Me@0 80 for( binIdx = 0; binIdx < hist->numBins; binIdx++ )
Me@0 81 {
Me@0 82 binStart = hist->startOfRange + hist->binWidth * binIdx;
Me@0 83 binEnd = binStart + hist->binWidth - 1;
Me@0 84 printf("bin range: %d - %d", binStart, binEnd );
Me@0 85
Me@0 86 numBars = hist->bins[ binIdx ] / barValue;
Me@0 87 //print one bin, height of bar is num dashes across page
Me@0 88 for( i = 0; i < numBars; i++ )
Me@0 89 {
Me@0 90 printf("-");
Me@0 91 }
Me@0 92 printf("\n");
Me@0 93 }
Me@0 94 }
Me@0 95