#include <vector>
#include <algorithm>
#include "histogram.h"
#include "histogram_internal.h"

using namespace std;

void find_minmax(const vector<double>& numbers, double& min, double& max) {
    if (numbers.empty()) {
        return;
    }

    min = numbers[0];
    max = numbers[0];

    for (double number : numbers) {
        if (number < min) {
            min = number;
        }
        if (number > max) {
            max = number;
        }
    }
}

vector<unsigned int> make_histogram(const vector<double>& numbers, size_t bin_count) {
    double min, max;
    find_minmax(numbers, min, max);

    vector<unsigned int> bins(bin_count);
    double bin_size = (max - min) / bin_count;

    for (double number : numbers) {
        bool found = false;
        for (size_t i = 0; i < bin_count - 1; i++) {
            auto lo = min + i * bin_size;
            auto hi = min + (i + 1) * bin_size;
            if (lo <= number && number < hi) {
                bins[i]++;
                found = true;
                break;
            }
        }
        if (!found) {
            bins[bin_count - 1]++;
        }
    }

    return bins;
}
