How to perform a vertical bar chart with the # character in c ++?

1

Performing a C ++ job here from college:

How to make a vertical graph in bars, that is, from bottom to top, of some vector.

Assuming there is a vector with some positions, for example v [3], where each position is a user that contains a value. The graph should contain this amount.

Assuming that V [0] has 5, V [1] has 6 and V [2] has 4. The total is 15, in this case, then the graph should be proportional, that is, 5 is 33.33% and successively.

    
asked by anonymous 29.04.2014 / 23:52

1 answer

4

If you get it right, you want to draw N bars each with height H k . As the output is horizontal you have to go by drawing a piece of each bar at a time before jumping the line. Then first find the maximum element (the highest bar) and then do that number of iterations. In each draws the bar if its value is greater than or equal to the current iteration.

Here's a simple code that does this:

#include <iostream>
#include <vector>
#include <algorithm>

void printBottomUpBarChart(const std::vector<int>& levels) {
    int highest = *std::max_element(levels.begin(), levels.end());
    for (int level = highest; level > 0; --level) {
        for (unsigned i = 0; i < levels.size(); ++i) {
            if (levels[i] >= level)
                std::cout << " #";
            else
                std::cout << "  ";
        }
        std::cout << std::endl;
    }
}

An example usage:

int main()
{
    std::vector<int> lvs;
    lvs.push_back(3);
    lvs.push_back(8);
    lvs.push_back(1);
    lvs.push_back(2);
    lvs.push_back(0);
    lvs.push_back(5);
    printBottomUpBarChart(lvs);
    return 0;
}

And the output:

   #        
   #        
   #        
   #       #
   #       #
 # #       #
 # #   #   #
 # # # #   #

If you have other values and want to draw the graph being proportional to these values but not exactly using them for the # number, scale the vector before moving to the function. I suggest rounding up always ( std::ceil(1.0 * x * targetHeight / actualHeight) ).

    
30.04.2014 / 15:33