Group stock by how soon it expires
A food depot dashboard puts every batch into one of four buckets so staff can see what to move first.
- Below zero days is "expired"; 0 to 7 is "week"; 8 to 30 is "month"; anything more is "later".
- All four keys appear in the result, even when the count is zero.
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.
Where you start
std::map<std::string, int> expiryBuckets(std::vector<int> daysLeft) {
}
Worked examples
| Call | Result |
|---|---|
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;
}