view Histogram.c @ 5:13b8591dd045

added addInterval -- is old version, have to merge with VMS__malloc version
author SeanHalle
date Thu, 11 Nov 2010 05:37:07 -0800
parents 6e864a0cb520
children a2388fae93ff
line source
1 /*
2 * Copyright 2010 OpenSourceStewardshipFoundation.org
3 * Licensed under GNU General Public License version 2
4 *
5 * Author: seanhalle@yahoo.com
6 *
7 */
9 #include "Histogram.h"
10 #include <malloc.h>
13 /*This Histogram Abstract Data Type has a number of bins plus a range of
14 * values that the bins span, both chosen at creation.
15 *
16 *One creates a Histogram instance using the makeHistogram function, then
17 * updates it with the addToHist function, and prints it out with the
18 * printHist function.
19 *
20 *Note, the bin width is an integer, so the end of the range is adjusted
21 * accordingly. Use the bin-width to calculate the bin boundaries.
22 */
25 Histogram *
26 makeHistogram( int32 numBins, int32 startOfRange, int32 endOfRange )
27 {
28 Histogram *hist;
29 int32 i;
31 hist = malloc( sizeof(Histogram) );
32 hist->bins = malloc( numBins * sizeof(int32) );
34 hist->numBins = numBins;
35 hist->binWidth = (endOfRange - startOfRange) / numBins;
36 hist->endOfRange = startOfRange + hist->binWidth * numBins;
37 hist->startOfRange = startOfRange;
39 for( i = 0; i < hist->numBins; i++ )
40 {
41 hist->bins[ i ] = 0;
42 }
44 return hist;
45 }
47 void inline
48 addToHist( int32 value, Histogram *hist )
49 {
50 int32 binIdx;
52 if( value < hist->startOfRange )
53 { binIdx = 0;
54 }
55 else if( value > hist->endOfRange )
56 { binIdx = hist->numBins - 1;
57 }
58 else
59 {
60 binIdx = (value - hist->startOfRange) / hist->binWidth;
61 }
63 hist->bins[ binIdx ] += 1;
64 }
67 void inline
68 addIntervalToHist( int32 startIntvl, int32 endIntvl, Histogram *hist )
69 {
70 int32 value;
72 value = endIntvl - startIntvl;
73 if( value < 0 || value > 10000000 ) return; //sanity check
74 addToHist( value, hist );
75 }
77 void
78 printHist( Histogram *hist )
79 {
80 int32 binIdx, i, numBars, maxHeight, barValue, binStart, binEnd;
82 maxHeight = 0;
83 for( i = 0; i < hist->numBins; i++ )
84 {
85 if( maxHeight < hist->bins[ i ] ) maxHeight = hist->bins[ i ];
86 }
87 barValue = maxHeight / 60; //60 spaces across page for tallest bin
89 printf("histogram: \n");
90 if( barValue == 0 ) printf("error printing histogram\n");
91 for( binIdx = 0; binIdx < hist->numBins; binIdx++ )
92 {
93 binStart = hist->startOfRange + hist->binWidth * binIdx;
94 binEnd = binStart + hist->binWidth - 1;
95 printf("bin range: %d - %d", binStart, binEnd );
97 numBars = hist->bins[ binIdx ] / barValue;
98 //print one bin, height of bar is num dashes across page
99 for( i = 0; i < numBars; i++ )
100 {
101 printf("-");
102 }
103 printf("\n");
104 }
105 }