Couple things.
1. Format your histogram labels so that the base of the histogram lines up.
2. Use an array (or better, a vector) for your histogram bins.
2. You'll probably need to scale your histogram. If you take a thousand samples, The size of a 1:1 scale histogram is going to be way too big to display on the console. For example, with a thousand samples being placed into 5 bins, assuming roughly even distribution, you'll have 200 samples per bin, or histogram bars ~200 asterisks long. If you scale the histogram by a factor of 10, then the histogram bars will be ~20 asterisks long.
Of course, if your sample size is only 100 samples, that's roughly 20 samples per bing, and with a scale of 10, that's only 2 asterisks per bin.
So, you need a sliding scale, based on the histogram size. After taking all the samples, and filling all the bins, find the largest bin size. Once you have that largest bin, calculate a scale factor that will give you the optimally sized histogram. The easiest way to do this is to divide the largest bin by your optimal histogram size (say, max bar size is limit to 30). Round that value UP to the largest whole number, and that's your scale factor.
Here's some sample code that generates Craps die rolls for reference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
vector<int> histogram_bins(11, 0);
int num_samples, rand_num, largest_bin, scale_size, counter;
string actvals = "Count ";
string dienum = "Roll";
//Prompt for sample size
do{
cout << "Input number of die rolls to generate (100-10,000): ";
cin >> num_samples;
if(num_samples < 100 || num_samples > 10000){
cout << "Incorrect Number of samples";
num_samples = 0;
}
}while(0 == num_samples);
//Generate random craps rolls and stash in appropriate bins
for(int x = 0; x < num_samples; x++){
//roll the dice
rand_num = (rand() % 6 + 1) + (rand() % 6 + 1);
histogram_bins[rand_num-2]++;
}
//Find the largest_bin
largest_bin = 0;
for(unsigned int x=1; x < histogram_bins.size(); x++)
if(histogram_bins[x] > histogram_bins[largest_bin])
largest_bin = x;
//Determine scale factor
//We want the largest bar to be no more than 30 asterisks
//integer division truncates, so we add 1 to effectively round up
scale_size = histogram_bins[largest_bin]/30 + 1;
cout << "Scale = " << scale_size << endl << endl;
//Now we create our histogram
cout << actvals << dienum << " Histogram" << endl;
cout.setf(ios::left);
for(unsigned int x = 0; x < histogram_bins.size(); x++){
cout.width(actvals.size());
cout << histogram_bins[x];
cout.width(dienum.size());
cout << x+2 << ":";
counter = 0;
while(counter++*scale_size < histogram_bins[x])
cout << "*";
cout << endl;
}
| |