Problems › JavaScript › logistics
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
Where you start
function nearestDepot(depots, x, y) {
}
Worked examples
| Call | Result |
|---|---|
nearestDepot([{"x":0,"y":0},{"x":10,"y":0},{"x":3,"y":4}], 4, 4) | 2 |
nearestDepot([{"x":0,"y":0},{"x":2,"y":2}], 1, 1) | 0 |
nearestDepot([{"x":9,"y":9}], 0, 0) | 0 |
nearestDepot([], 0, 0) | -1 |
Hint
Track a best index while you walk the list.
Reference solution in JavaScript
function nearestDepot(depots, x, y) {
let best = -1, bestDist = Infinity;
for (let i = 0; i < depots.length; i++) {
const d = Math.abs(depots[i].x - x) + Math.abs(depots[i].y - y);
if (d < bestDist) { bestDist = d; best = i; }
}
return best;
}