#include #include using namespace std; struct Input { vector numbers; size_t bin_count = 0; }; Input input_data() { Input in; int number_count; do { cerr << "Enter number count: "; cin >> number_count; } while (number_count < 1); do { cerr << "Enter bucket: "; cin >> in.bin_count; } while (in.bin_count < 1); cerr << "\n"; in.numbers.resize(number_count); for (int i = 0; i < number_count; i++) { cin >> in.numbers[i]; } return in; } void find_minmax(const vector& numbers, double& min, double& max) { if (numbers.empty()) return; min = numbers[0]; max = numbers[0]; for (double x : numbers) { if (x < min) min = x; if (x > max) max = x; } } vector make_histogram(const vector& numbers, size_t bin_count) { double min, max; find_minmax(numbers, min, max); float k = (max - min) / bin_count; vector bins(bin_count, 0); for (double num : numbers) { bool flag = false; for (size_t j = 0; j < bin_count && !flag; j++) { if (num >= (min + k * j) && num < (min + k * (j + 1))) { bins[j]++; flag = true; } } if (!flag) bins[bin_count - 1]++; } return bins; } void show_histogram_text(const vector& bins) { const size_t SCREEN_WIDTH = 80; const size_t MAX_ASTERISK = SCREEN_WIDTH - 3 - 1; int max_count = 0; for (int count : bins) { if (count > max_count) max_count = count; } for (size_t j = 0; j < bins.size(); j++) { if (bins[j] < 100) cout << " "; if (bins[j] < 10) cout << " "; cout << bins[j] << "|"; size_t height = bins[j]; if (max_count > MAX_ASTERISK) { if (max_count != bins[j]) { height = static_cast(MAX_ASTERISK * (static_cast(bins[j]) / max_count)); } else if (max_count == bins[j]) { height = MAX_ASTERISK; } } for (size_t i = 0; i < height; i++) cout << "*"; cout << "\n"; } } int main() { auto input = input_data(); auto bins = make_histogram(input.numbers, input.bin_count); show_histogram_text(bins); return 0; }