From 17cabe7773137c777d75379284ed600df5c5e500 Mon Sep 17 00:00:00 2001 From: Tom Smeding Date: Sat, 14 Sep 2019 12:49:22 +0200 Subject: Code cleanup --- histogram.cpp | 167 +++++++++++++++++++++++++++++----------------------------- 1 file changed, 84 insertions(+), 83 deletions(-) diff --git a/histogram.cpp b/histogram.cpp index 5bb2133..855776d 100644 --- a/histogram.cpp +++ b/histogram.cpp @@ -3,140 +3,141 @@ #include #include #include +#include #include #include -using namespace std; +static const char *argv0; -const char *argv0; - -void usage(){ - cerr<<"Usage: "< ] []"< ] []" << std::endl + << "Prints a simple histogram of stdin data in your terminal, using" << std::endl + << "either the given lower and upper bounds, or the minimum and" << std::endl + << "maximum extracted from the data." << std::endl + << "The number of bins can also be passed." << std::endl + << "Data on stdin is assumed to be a list of floating-point values." << std::endl; } -double parsefloat(const char *s,const char *errprefix){ +double parsefloat(const char *s, const char *errprefix) { char *endp; - double v=strtod(s,&endp); - if(!s[0]||*endp){ - cerr< values; - while(true){ + double minval = INFINITY, maxval = -INFINITY; + std::vector values; + while (true) { double v; - cin>>v; - if(!cin)break; + std::cin >> v; + if (!std::cin) break; values.push_back(v); - if(vmaxval)maxval=v; + if (v < minval) minval = v; + if (v > maxval) maxval = v; } - if(!havebounds){ - low=minval; - high=maxval; + if (!havebounds) { + low = minval; + high = maxval; } - sort(values.begin(),values.end()); + std::sort(values.begin(), values.end()); - vector histogram(nbins); + std::vector histogram(nbins); - int binidx=0,tally=0,maxtally=-1; - for(double v : values){ - if(vhigh){ - // cerr<<"Point "< high) { + // cerr << "Point " << v << " out of range!" << endl; continue; } - int bin=(v-low)/(high-low)*nbins; - if(bin==nbins)bin--; - assert(bin>=0&&binmaxtally)maxtally=tally; - binidx=bin; - tally=0; + int64_t bin = (v - low) / (high - low) * nbins; + if (bin == nbins) bin--; + assert(bin >= 0 && bin < nbins); + if (bin != binidx) { + histogram[binidx] = tally; + if (tally > maxtally) maxtally = tally; + binidx = bin; + tally = 0; } tally++; } - histogram[binidx]=tally; - if(tally>maxtally)maxtally=tally; + histogram[binidx] = tally; + if (tally > maxtally) maxtally = tally; - if(maxtally==0){ - cerr<<"histogram: No data in range"<