Drill

ProblemsC++ › reporting

Bucket some readings

mediumreportingHash mapsArraysMathC++

A chart needs counts per band rather than raw readings — how many orders fell between 0 and 9, 10 and 19, and so on.

histogram(values: list<int>, bucketSize: int) → map<string, int>

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

std::map<std::string, int> histogram(std::vector<int> values, int bucketSize) {
    
}

Worked examples

CallResult
histogram(std::vector<int>{0, 5, 10, 15, 23}, 10)std::map<std::string, int>{{std::string("0"), 2}, {std::string("10"), 2}, {std::string("20"), 1}}
histogram(std::vector<int>{9, 10}, 10)std::map<std::string, int>{{std::string("0"), 1}, {std::string("10"), 1}}
histogram(std::vector<int>{1, 2, 3}, 1)std::map<std::string, int>{{std::string("1"), 1}, {std::string("2"), 1}, {std::string("3"), 1}}
histogram(std::vector<int>{1, 2}, 0)std::map<std::string, int>{}

Hint

Integer-divide by the bucket size, multiply back, and that is the bucket name.

Reference solution in C++
std::map<std::string, int> histogram(std::vector<int> values, int bucketSize) {
    std::map<string, int> result;
    if (bucketSize <= 0) return result;
    for (int v : values) {
        result[std::to_string(v / bucketSize * bucketSize)]++;
    }
    return result;
}

The same problem in another language

More reporting problems in C++