Drill

ProblemsC++ › inventory

Group stock by how soon it expires

mediuminventoryHash mapsArraysC++

A food depot dashboard puts every batch into one of four buckets so staff can see what to move first.

expiryBuckets(daysLeft: list<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> expiryBuckets(std::vector<int> daysLeft) {
    
}

Worked examples

CallResult
expiryBuckets(std::vector<int>{-1, 0, 7, 8, 30, 31, 400})std::map<std::string, int>{{std::string("expired"), 1}, {std::string("week"), 2}, {std::string("month"), 2}, {std::string("later"), 2}}
expiryBuckets(std::vector<int>{})std::map<std::string, int>{{std::string("expired"), 0}, {std::string("week"), 0}, {std::string("month"), 0}, {std::string("later"), 0}}
expiryBuckets(std::vector<int>{-5, -5, -5})std::map<std::string, int>{{std::string("expired"), 3}, {std::string("week"), 0}, {std::string("month"), 0}, {std::string("later"), 0}}
expiryBuckets(std::vector<int>{0})std::map<std::string, int>{{std::string("expired"), 0}, {std::string("week"), 1}, {std::string("month"), 0}, {std::string("later"), 0}}

Hint

Seed the map with all four keys at zero first, then walk the list once.

Reference solution in C++
std::map<std::string, int> expiryBuckets(std::vector<int> daysLeft) {
    std::map<string, int> out{{"expired", 0}, {"week", 0}, {"month", 0}, {"later", 0}};
    for (int d : daysLeft) {
        if (d < 0) out["expired"]++;
        else if (d <= 7) out["week"]++;
        else if (d <= 30) out["month"]++;
        else out["later"]++;
    }
    return out;
}

The same problem in another language

More inventory problems in C++