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
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
public int RouteCost(List<Leg> legs) {
}
Worked examples
| Call | Result |
|---|---|
RouteCost(new List<Leg> { new Leg(10, 5), new Leg(4, 8) }) | 82 |
RouteCost(new List<Leg> { new Leg(1, 1000) }) | 1000 |
RouteCost(new List<Leg> { }) | 0 |
RouteCost(new List<Leg> { new Leg(0, 500) }) | 0 |
Hint
Multiply per leg and add.
Reference solution in C#
public int RouteCost(List<Leg> legs) {
int total = 0;
foreach (var leg in legs) total += leg.Distance * leg.Rate;
return total;
}