From 4697ceca46be6378216f468646a8ce797f5b5512 Mon Sep 17 00:00:00 2001 From: alextwix Date: Fri, 25 Apr 2025 03:18:18 +0300 Subject: [PATCH] update --- .gitignore | 3 ++ histogram.cpp | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++ histogram.h | 13 ++++++++ 3 files changed, 99 insertions(+) create mode 100644 .gitignore create mode 100644 histogram.cpp create mode 100644 histogram.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9f9ed71 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +lab3.vcxproj +lab3.vcxproj.filters +lab3.vcxproj.user diff --git a/histogram.cpp b/histogram.cpp new file mode 100644 index 0000000..ea528ad --- /dev/null +++ b/histogram.cpp @@ -0,0 +1,83 @@ +#include "histogram.h" +#include +#include + +Input input_data() { + Input in; + size_t number_count; + + std::cerr << "Enter number count: "; + std::cin >> number_count; + + in.numbers.resize(number_count); + std::cerr << "Enter " << number_count << " numbers: "; + for (size_t i = 0; i < number_count; i++) { + std::cin >> in.numbers[i]; + } + + std::cerr << "Enter bin count: "; + std::cin >> in.bin_count; + + return in; +} + +static void find_minmax(const std::vector& numbers, double& min, double& max) { + min = std::numeric_limits::max(); + max = std::numeric_limits::lowest(); + + for (double x : numbers) { + if (x < min) min = x; + if (x > max) max = x; + } +} + +std::vector make_histogram(const std::vector& numbers, size_t bin_count) { + double min, max; + find_minmax(numbers, min, max); + + if (max == min) { + return std::vector(bin_count, numbers.size()); + } + + double bin_size = (max - min) / bin_count; + std::vector bins(bin_count, 0); + + for (double x : numbers) { + size_t bin_index = static_cast((x - min) / bin_size); + if (bin_index >= bin_count) bin_index = bin_count - 1; + bins[bin_index]++; + } + + return bins; +} + +void show_histogram_text(const std::vector& bins) { + const size_t SCREEN_WIDTH = 80; + const size_t MAX_ASTERISK = SCREEN_WIDTH - 3 - 1; + size_t max_count = 0; + + for (size_t count : bins) { + if (count > max_count) max_count = count; + } + + std::cerr << "Bin counts:" << std::endl; + + for (size_t j = 0; j < bins.size(); j++) { + size_t height = (max_count > MAX_ASTERISK) + ? static_cast(MAX_ASTERISK * (static_cast(bins[j]) / max_count)) + : bins[j]; + + if (bins[j] < 10) { + std::cout << " " << bins[j] << "|"; + } + else if (bins[j] < 100) { + std::cout << " " << bins[j] << "|"; + } + else { + std::cout << bins[j] << "|"; + } + + for (size_t k = 0; k < height; k++) std::cout << "*"; + std::cout << std::endl; + } +} diff --git a/histogram.h b/histogram.h new file mode 100644 index 0000000..d709e86 --- /dev/null +++ b/histogram.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +struct Input { + std::vector numbers; + size_t bin_count{}; +}; + +Input input_data(); +std::vector make_histogram(const std::vector& numbers, size_t bin_count); +void show_histogram_text(const std::vector& bins); +