Drill

ProblemsJavaScript › logistics

Which depot is closest

mediumlogisticsJavaScript

A last-mile sheet lists every depot as an x, y position on a grid. Pick the depot nearest a delivery point, Manhattan distance.

nearestDepot(depots: list<Point>, x: int, y: int) → int

Solve it in the editor →

Where you start

function nearestDepot(depots, x, y) {
  
}

Worked examples

CallResult
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;
}

The same problem in another language

More logistics problems in JavaScript