From 13bce3044591289de476fd97dfb9cf2c8b25b4a9 Mon Sep 17 00:00:00 2001 From: "Sasha (KobzevAV)" Date: Sun, 23 Apr 2023 23:03:14 +0300 Subject: [PATCH] header: histogram --- histogram.cpp | 37 +++++++++++++++++++++++++++++++++++++ histogram.h | 8 ++++++++ 2 files changed, 45 insertions(+) create mode 100644 histogram.cpp create mode 100644 histogram.h diff --git a/histogram.cpp b/histogram.cpp new file mode 100644 index 0000000..b3defde --- /dev/null +++ b/histogram.cpp @@ -0,0 +1,37 @@ +#include "histogram.h" +void +find_minmax(const std::vector& numbers, double& min, double& max){ + min = numbers[0]; + max = numbers[0]; + for (double x: numbers){ + if (min > x){ + min = x; + } + if (max < x){ + max = x; + } + } +} + +std::vector +make_histogram(const std::vector& numbers, size_t bin_count){ + double min, max; + std::vector bins(bin_count); + find_minmax(numbers, min, max); + double diff = (max - min) / bin_count; + for (double x: numbers){ + bool found = false; + for (size_t j = 0;(j < bin_count - 1) && !found; j++){ + auto lo = min + j * diff; + auto hi = min + (j + 1) * diff; + if ((lo <= x) && (hi > x)){ + bins[j]++; + found = true; + } + } + if(!found){ + bins[bin_count - 1]++; + } + } + return bins; +} diff --git a/histogram.h b/histogram.h new file mode 100644 index 0000000..11954ba --- /dev/null +++ b/histogram.h @@ -0,0 +1,8 @@ +#ifndef HISTOGRAM_H_INCLUDED +#define HISTOGRAM_H_INCLUDED +#include + + +std::vector +make_histogram(const std::vector& numbers, size_t bin_count); +#endif // HISTOGRAM_H_INCLUDED