Defining a scale factor to graph three quantities, the sum of which is constant

Viewed 49

I am trying to write a graph in standard output, the program returns rows of "#" that should add up to the initial quantity after another function changes them. I guarantee that the function that modifies the numbers is not at fault. This is my code :

struct mystruct {
    long long int s;
    long long int i;
    long long int r;
}

mystruct initial_;

void draw_row(mystruct P)
{
    long long int Ntotal = initial_.s + initial_.i;
    int scale = round(Ntotal / 10);
    std::string a(Ntotal / scale, '#');
    std::string b(round(P.s / scale), '#');
    std::string c(round(P.i / scale), '#');
    std::string d(round(P.r / scale), '#');
    std::cout << P.s << " " << P.i << " " << P.r << '\n';
    std::cout << scale << '\n';
    std::cout << a << '\n' << b << c << d << '\n';
}

These are examples of some of its outputs :

499 1 0
##########
#########

0 450 50
##########
##########

0 249 251
##########
#########
2 Answers

You are doing integer divisions in the lines

int scale = round(Ntotal/10) ; 
std::string a(Ntotal/scale,'#') ;
std::string b(round(P.s/scale),'#') ;
std::string c(round(P.i/scale),'#') ;
std::string d(round(P.r/scale),'#') ;

and the remainders are truncated, so round() used here aren't working as expected.

You can do (A + B/2) / B to round the division result of two positive integers A / B, so the lines should be

int scale = (Ntotal+5)/10 ; 
std::string a(Ntotal/scale,'#') ;
std::string b((P.s+scale/2)/scale,'#') ;
std::string c((P.i+scale/2)/scale,'#') ;
std::string d((P.r+scale/2)/scale,'#') ;

I take the first column drawn shows the max possible value, that is a = Ntotal = initial_.s + initial_.i >= P = P.s + P.i + P.r, everything divided by scale.

The second P.s + P.i + P.r column is sometimes shorter than the first Ntotal one because of the truncation error introduced by multiple integer divisions (scale = round(Ntotal/10) and b, c, d = round(P.(s, i, r)/scale)).

You cannot totally defeat the problem, but you can improve the representation by enlarging the scale, that is by reducing the scale parameter, which would stretch the columns longer (they will end up containing more #).

Related