@@ -35,6 +35,8 @@ VerticalBarChart::VerticalBarChart(std::string filename, int width, int height)
3535 if (height < 10 )
3636 height = 10 ;
3737 BarChartInfo info = getBarChartInfoFromFile (filename);
38+ if (width < info.dataPoints .size ()+2 )
39+ throw std::runtime_error (" width must be larger to display chart" );
3840 this ->title = info.title ;
3941 this ->dataPoints = info.dataPoints ;
4042 this ->width = width;
@@ -129,32 +131,40 @@ BarChartInfo getBarChartInfoFromFile(std::string filename)
129131 @returns A vector of strings line-by-line which make the ascii chart.
130132*/
131133std::vector<std::string> getVerticalBarChartLineStrings (
132- int width, int height, std::vector<ChartDataPoint> dataPoints)
134+ int width, int height,
135+ std::vector<ChartDataPoint> dataPoints)
133136{
134137 std::vector<std::string> lineStrings;
138+ std::vector<double > dataPointValues = getDataPointValues (dataPoints);
139+ double highestDataPointValue = *std::max_element (
140+ dataPointValues.begin (), dataPointValues.end ()
141+ );
135142 int spacesBetweenBars = width / dataPoints.size ();
136- double maxValue = getMaxDataPointValue (dataPoints);
137143 std::vector<std::pair<ChartDataPoint, int >> barHeights;
138144 for (auto i : dataPoints){
139- int currentHeight = i.value / maxValue * height;
140- barHeights.push_back (std::make_pair (i, currentHeight ));
145+ int barHeight = i.value / highestDataPointValue * height;
146+ barHeights.push_back (std::make_pair (i, barHeight ));
141147 }
142-
143- for (int lineNumber = height; lineNumber > 0 ; --lineNumber){
144- int currentDataPointIndex = 0 ;
148+ auto checkBarAppearsAtLine = [barHeights, height](int barHeightIndex, int line){
149+ if (line <= barHeights.at (barHeightIndex).second )
150+ return true ;
151+ return false ;
152+ };
153+ for (int lineNumber = height; lineNumber >= 0 ; --lineNumber){
154+ int currentBarIndex = 0 ;
145155 std::string currentLineString = " " ;
146- for (int currentColumn = 0 ; currentColumn < width; ++currentColumn ){
147- if (currentColumn % spacesBetweenBars != 0 ){
156+ for (int columnNumber = 0 ; columnNumber < width; ++columnNumber ){
157+ if (columnNumber % spacesBetweenBars != 0 ){
148158 currentLineString += " " ;
149159 continue ;
150160 }
151- if (lineNumber <= barHeights.at (currentDataPointIndex).second )
161+ if (currentBarIndex == barHeights.size ())
162+ break ;
163+ if (checkBarAppearsAtLine (currentBarIndex, lineNumber))
152164 currentLineString += VERTICAL_BAR_CHAR;
153165 else
154166 currentLineString += " " ;
155- if (currentDataPointIndex + 1 == barHeights.size ())
156- break ;
157- ++currentDataPointIndex;
167+ ++currentBarIndex;
158168 }
159169 lineStrings.push_back (currentLineString);
160170 }
0 commit comments