Mercurial > cgi-bin > hgwebdir.cgi > VMS > C_Libraries > Histogram
view Histogram.c @ 1:dbb58ebfd690
testing
| author | Me |
|---|---|
| date | Sat, 11 Sep 2010 04:46:29 -0700 |
| parents | |
| children | 3d35477a5121 13b8591dd045 |
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( int numBins, int startOfRange, int endOfRange )
27 {
28 Histogram *hist;
29 int i;
31 hist = malloc( sizeof(Histogram) );
32 hist->bins = malloc( numBins * sizeof(int) );
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
48 addToHist( int value, Histogram *hist )
49 {
50 int 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 }
66 void
67 printHist( Histogram *hist )
68 {
69 int binIdx, i, numBars, maxHeight, barValue, binStart, binEnd;
71 maxHeight = 0;
72 for( i = 0; i < hist->numBins; i++ )
73 {
74 if( maxHeight < hist->bins[ i ] ) maxHeight = hist->bins[ i ];
75 }
76 barValue = maxHeight / 60; //60 spaces across page for tallest bin
78 printf("histogram: \n");
79 if( barValue == 0 ) printf("error printing histogram\n");
80 for( binIdx = 0; binIdx < hist->numBins; binIdx++ )
81 {
82 binStart = hist->startOfRange + hist->binWidth * binIdx;
83 binEnd = binStart + hist->binWidth - 1;
84 printf("bin range: %d - %d", binStart, binEnd );
86 numBars = hist->bins[ binIdx ] / barValue;
87 //print one bin, height of bar is num dashes across page
88 for( i = 0; i < numBars; i++ )
89 {
90 printf("-");
91 }
92 printf("\n");
93 }
94 }
