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<double>& 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<size_t> +make_histogram(const std::vector<double>& numbers, size_t bin_count){ + double min, max; + std::vector <size_t> 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 <vector> + + +std::vector<size_t> +make_histogram(const std::vector<double>& numbers, size_t bin_count); +#endif // HISTOGRAM_H_INCLUDED