Drill

ProblemsC++ › orders

Total a basket that came off a queue

easyordersArraysMathC++

Order lines arrive from a message queue and the payload is not always clean: a line can be missing entirely, and quantities have been seen at zero.

orderTotal(lines: list<Line?>) → 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

int orderTotal(std::vector<std::optional<Line>> lines) {
    
}

Worked examples

CallResult
orderTotal(std::vector<std::optional<Line>>{std::optional<Line>(Line{std::string("A"), 2, 100}), std::optional<Line>(Line{std::string("B"), 3, 50})})350
orderTotal(std::vector<std::optional<Line>>{std::optional<Line>(Line{std::string("A"), 1, 10}), std::nullopt, std::optional<Line>(Line{std::string("C"), 2, 5})})20
orderTotal(std::vector<std::optional<Line>>{std::optional<Line>(Line{std::string("A"), 0, 999}), std::optional<Line>(Line{std::string("B"), -1, 999})})0
orderTotal(std::vector<std::optional<Line>>{})0

Hint

Guard inside the loop, not before it. One bad line should not cost you the rest.

Reference solution in C++
int orderTotal(std::vector<std::optional<Line>> lines) {
    int total = 0;
    for (const auto& l : lines) {
        if (!l.has_value() || l->qty <= 0) continue;
        total += l->qty * l->unitPrice;
    }
    return total;
}

The same problem in another language

More orders problems in C++