diff --git a/histogram.cpp b/histogram.cpp new file mode 100644 index 0000000..ec14323 --- /dev/null +++ b/histogram.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include "histogram.h" +using namespace std; + + +static void find_minmax(const vector& numbers, double& mini, double& maxi) { + + mini = numbers[0]; + maxi = numbers[0]; + for (double x : numbers) { + if (x < mini) { + mini = x; + } + else if (x > maxi) { + maxi = x; + } + } +} +vector +make_histogram(const vector& numbers, size_t bin_count) { + double mini, maxi; + find_minmax(numbers, mini, maxi); + + vector bins(bin_count); + + double bin_size = (maxi - mini) / bin_count; + for (double num : numbers) { + bool found = false; + for (size_t j = 0; (j < bin_count - 1) && !found; j++){ + auto lo = mini + j * bin_size; + auto hi = mini + (j + 1) * bin_size; + if ((lo <= num) && (num < hi)) { + 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..a86c9a3 --- /dev/null +++ b/histogram.h @@ -0,0 +1,5 @@ +#pragma once +#include + +std::vector +make_histogram(const std::vector& numbers, size_t bin_count); diff --git a/text.cpp b/text.cpp new file mode 100644 index 0000000..37fe5c2 --- /dev/null +++ b/text.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include "text.h" +using namespace std; + +void +show_histogram_text(const vector& bins, size_t bin_count) { + size_t max_count = bins[0]; + for (size_t i = 0; i < bin_count; i++) { + if (bins[i] > max_count) { + max_count = bins[i]; + } + } + + vector height(bin_count); + for (size_t i = 0; i < bin_count; i++) { + if (max_count > MAX_ASTERISK) { + height[i] = round(MAX_ASTERISK * (static_cast(bins[i]) / max_count)); + } else { + height[i] = bins[i]; + } + } + + for (size_t i = 0; i < bin_count; i++) { + if (bins[i] < 10) { + cout << " "; + } else if (bins[i] < 100) { + cout << " "; + } + cout << bins[i] << "| "; + + for (size_t j = 0; j < height[i]; j++) { + cout << " * "; + } + cout << endl; + } +} diff --git a/text.h b/text.h new file mode 100644 index 0000000..db04afe --- /dev/null +++ b/text.h @@ -0,0 +1,5 @@ +#pragma once +#include + +void +show_histogram_text(const vector& bins, size_t bin_count);