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
Go 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
func routeCost(legs []Leg) int {
}
Worked examples
| Call | Result |
|---|---|
routeCost([]Leg{Leg{Distance: 10, Rate: 5}, Leg{Distance: 4, Rate: 8}}) | 82 |
routeCost([]Leg{Leg{Distance: 1, Rate: 1000}}) | 1000 |
routeCost([]Leg{}) | 0 |
routeCost([]Leg{Leg{Distance: 0, Rate: 500}}) | 0 |
Hint
Multiply per leg and add.
Reference solution in Go
func routeCost(legs []Leg) int {
total := 0
for _, leg := range legs {
total += leg.Distance * leg.Rate
}
return total
}