Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
87 строки
2.0 KiB
C++
87 строки
2.0 KiB
C++
#include <iostream>
|
|
#include "histogram.h"
|
|
#include "histogram_internal.h"
|
|
#include <algorithm>
|
|
#include <cmath>
|
|
#include <vector>
|
|
using namespace std;
|
|
|
|
int find_minmax(const std::vector<double>& numbers, double& min, double& max) {
|
|
if(numbers.size()){
|
|
min = numbers[0];
|
|
max = numbers[0];
|
|
}
|
|
|
|
|
|
for (double num : numbers) {
|
|
if (num < min) min = num;
|
|
if (num > max) max = num;
|
|
}
|
|
return numbers.size();
|
|
}
|
|
|
|
std::vector<size_t> make_histogram(const std::vector<double>& numbers, size_t bin_count) {
|
|
if (numbers.empty() || bin_count == 0) return {};
|
|
|
|
double min, max;
|
|
find_minmax(numbers, min, max);
|
|
|
|
std::vector<size_t> bins(bin_count);
|
|
double bin_size = (max - min) / bin_count;
|
|
|
|
for (double num : numbers) {
|
|
bool found = false;
|
|
for (size_t j = 0; j < bin_count - 1 && !found; ++j) {
|
|
double lo = min + j * bin_size;
|
|
double hi = min + (j + 1) * bin_size;
|
|
if (lo <= num && num < hi) {
|
|
bins[j]++;
|
|
found = true;
|
|
}
|
|
}
|
|
if (!found) {
|
|
bins[bin_count - 1]++;
|
|
}
|
|
}
|
|
|
|
return bins;
|
|
}
|
|
|
|
Input input_data() {
|
|
Input in;
|
|
std::cin >> in.number_count;
|
|
|
|
in.numbers.resize(in.number_count);
|
|
for (size_t i = 0; i < in.number_count; i++) {
|
|
std::cin >> in.numbers[i];
|
|
}
|
|
|
|
std::cin >> in.bin_count;
|
|
return in;
|
|
}
|
|
|
|
void show_histogram_text(const vector<size_t>& bins, size_t block_width) {
|
|
if (bins.empty()) return;
|
|
|
|
const size_t max_count = *max_element(bins.begin(), bins.end());
|
|
if (max_count == 0) return;
|
|
|
|
|
|
const size_t max_console_width = 60;
|
|
|
|
|
|
const double scale = static_cast<double>(max_console_width) / max_count;
|
|
|
|
for (size_t count : bins) {
|
|
|
|
size_t stars = static_cast<size_t>(count * scale);
|
|
|
|
|
|
if (count < 100) cout << " ";
|
|
if (count < 10) cout << " ";
|
|
|
|
cout << count << "|";
|
|
cout << string(stars, '*') << endl;
|
|
}
|
|
}
|