diff --git a/histogram.cpp b/histogram.cpp new file mode 100644 index 0000000..dd5f5ed --- /dev/null +++ b/histogram.cpp @@ -0,0 +1,79 @@ +#include +#include "histogram.h" +#include "histogram_internal.h" +#include +#include + + +void find_minmax(const std::vector& numbers, double& min, double& max) { + if (numbers.empty()) return; + + min = numbers[0]; + max = numbers[0]; + for (double num : numbers) { + if (num < min) min = num; + if (num > max) max = num; + } +} + +std::vector make_histogram(const std::vector& numbers, size_t bin_count) { + if (numbers.empty() || bin_count == 0) return {}; + + double min, max; + find_minmax(numbers, min, max); + + std::vector 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 std::vector& bins, size_t max_width) { + if (bins.empty()) return; + + size_t max_count = *std::max_element(bins.begin(), bins.end()); + if (max_count == 0) return; + + for (size_t count : bins) { + + if (count < 100) std::cout << " "; + if (count < 10) std::cout << " "; + + std::cout << count << "|"; + + + size_t bar_length = (count * max_width) / max_count; + for (size_t i = 0; i < bar_length; ++i) { + std::cout << "*"; + } + std::cout << std::endl; + } +} diff --git a/histogram.h b/histogram.h new file mode 100644 index 0000000..05847f1 --- /dev/null +++ b/histogram.h @@ -0,0 +1,17 @@ +#ifndef HISTOGRAM_H +#define HISTOGRAM_H + +#include + +struct Input { + std::vector numbers; + size_t bin_count{}; + size_t number_count; +}; + + +Input input_data(); +std::vector make_histogram(const std::vector& numbers, size_t bin_count); +void show_histogram_text(const std::vector& bins, size_t max_width = 80); + +#endif diff --git a/histogram_internal.h b/histogram_internal.h new file mode 100644 index 0000000..4ca4ae4 --- /dev/null +++ b/histogram_internal.h @@ -0,0 +1,8 @@ +#ifndef HISTOGRAM_INTERNAL_H +#define HISTOGRAM_INTERNAL_H + +#include + +void find_minmax(const std::vector& numbers, double& min, double& max); + +#endif