Cost of a planned route
A route is a list of legs; each leg has a distance and a per-kilometre rate. Sum the cost of the whole route.
- A leg contributes distance × rate.
- An empty route costs zero.
routeCost(legs: list<Leg>) → int
Java 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
int routeCost(List<Leg> legs) {
}
Worked examples
| Call | Result |
|---|---|
routeCost(Main.<Leg>ls(new Leg(10, 5), new Leg(4, 8))) | 82 |
routeCost(Main.<Leg>ls(new Leg(1, 1000))) | 1000 |
routeCost(Main.<Leg>ls()) | 0 |
routeCost(Main.<Leg>ls(new Leg(0, 500))) | 0 |
Hint
Multiply per leg and add.
Reference solution in Java
int routeCost(List<Leg> legs) {
int total = 0;
for (Leg leg : legs) total += leg.distance * leg.rate;
return total;
}