diff --git a/histogram.cpp b/histogram.cpp new file mode 100644 index 0000000..f23db86 --- /dev/null +++ b/histogram.cpp @@ -0,0 +1,47 @@ +#include +#include +#include "histogram.h" +using namespace std; + +void +find_minmax(const vector& numbers, double& min, double& max) { + min = numbers[0]; + for (size_t i = 1; i < numbers.size(); i++) { + if (numbers[i] < min) { + min = numbers[i]; + } + else if (numbers[i] > max) { + max = numbers[i]; + } + } +} + +vector +make_histogram(const vector & numbers, size_t bin_count) { + double minc, maxc; + find_minmax(numbers, minc, maxc); + vector bins(bin_count); + double bin_size = (maxc - minc) / bin_count; + size_t bin_max_size = 0; + for (size_t i = 0; i < numbers.size(); i++) { + bool found = false; + for (size_t j = 0; (j < bin_count - 1) && !found; j++) { + auto lo = minc + j * bin_size; + auto hi = minc + (j + 1) * bin_size; + if ((lo <= numbers[i]) && (numbers[i] < hi)) { + bins[j]++; + found = true; + if (bins[j] > bin_max_size) { + bin_max_size = bins[j]; + } + } + } + if (!found) { + bins[bin_count - 1]++; + if (bins[bin_count - 1] > bin_max_size) { + bin_max_size = bins[bin_count - 1]; + } + } + } + return bins; +} \ No newline at end of file diff --git a/histogram.h b/histogram.h new file mode 100644 index 0000000..58b7e67 --- /dev/null +++ b/histogram.h @@ -0,0 +1,7 @@ +#pragma once + +#include + +std::vector +make_histogram(const std::vector& numbers, size_t bin_count); +