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
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 NearestDepot(List<Point> depots, int x, int y) {
}
Worked examples
| Call | Result |
|---|---|
NearestDepot(new List<Point> { new Point(0, 0), new Point(10, 0), new Point(3, 4) }, 4, 4) | 2 |
NearestDepot(new List<Point> { new Point(0, 0), new Point(2, 2) }, 1, 1) | 0 |
NearestDepot(new List<Point> { new Point(9, 9) }, 0, 0) | 0 |
NearestDepot(new List<Point> { }, 0, 0) | -1 |
Hint
Track a best index while you walk the list.
Reference solution in C#
public int NearestDepot(List<Point> depots, int x, int y) {
int best = -1, bestDist = int.MaxValue;
for (int i = 0; i < depots.Count; i++) {
var p = depots[i];
int d = Math.Abs(p.X - x) + Math.Abs(p.Y - y);
if (d < bestDist) { bestDist = d; best = i; }
}
return best;
}