Which depot is closest
A last-mile sheet lists every depot as an x, y position on a grid. Pick the depot nearest a delivery point, Manhattan distance.
- Distance is |x1 - x2| + |y1 - y2|, in whole units.
- A tie is broken by whoever comes first in the list.
- With no depots at all return -1.
nearestDepot(depots: list<Point>, x: int, y: int) → 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 nearestDepot(depots []Point, x int, y int) int {
}
Worked examples
| Call | Result |
|---|---|
nearestDepot([]Point{Point{X: 0, Y: 0}, Point{X: 10, Y: 0}, Point{X: 3, Y: 4}}, 4, 4) | 2 |
nearestDepot([]Point{Point{X: 0, Y: 0}, Point{X: 2, Y: 2}}, 1, 1) | 0 |
nearestDepot([]Point{Point{X: 9, Y: 9}}, 0, 0) | 0 |
nearestDepot([]Point{}, 0, 0) | -1 |
Hint
Track a best index while you walk the list.
Reference solution in Go
func nearestDepot(depots []Point, x int, y int) int {
best, bestDist := -1, int(^uint(0) >> 1)
for i, p := range depots {
d := p.X - x
if d < 0 {
d = -d
}
s := p.Y - y
if s < 0 {
s = -s
}
if d+s < bestDist {
bestDist = d + s
best = i
}
}
return best
}