#include "algorithm.h"
#include <util/generic/deque.h>

namespace NPrivate {

    ui64 AverageValue(const TCountByValue& values, ui64 average, ui32 attemp) {
        if (!attemp)
            return average;
        TDeque<std::pair<ui32, ui64> > groups;
        ui64 grSum = 0;
        ui32 grCount = 0;
        ui64 prev = 0;
        for (const auto& val : values) {
            if (grCount && val.first > 0.1 * average + prev) {
                groups.push_back(std::pair<ui32, ui64>(grSum / grCount, grCount));
                grCount = 0;
                grSum = 0;
            }
            grCount += val.second;
            grSum += val.second * val.first;
            prev = val.first;
        }
        if (grCount)
            groups.push_back(std::pair<ui32, ui64>(grSum / grCount, grCount));
        if (groups.size() > 1)
            groups.pop_front();
        if (groups.size() > 1)
            groups.pop_back();
        ui64 sum = 0;
        ui32 count = 0;
        for (const auto& val : groups) {
            sum += val.second * val.first;
            count += val.second;
        }
        ui64 res = sum / count;
        if (res == average)
            return average;
        return AverageValue(values, res, attemp - 1);
    }
}
