Best Position for a Service Centre LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} positions
3
* @return {number}
4
*/
5
var getMinDistSum = function (positions) {
6
/**
7
identify the vertical range and horizontal range
8

9
start from the center of positions
10
calc the distance
11
test the 4 direction with a certain step
12
if any distance is closer, choose it as the new candidate
13
if all 4 are further, reduce the step
14
**/
15

16
let xSum = 0;
17
let ySum = 0;
18
for (const [x, y] of positions) {
19
xSum += x;
20
ySum += y;
21
}
22

23
let n = positions.length;
24
let x = xSum / n;
25
let y = ySum / n;
26

27
let step = 0.5;
28
const dirs = [
29
[0, 1],
30
[0, -1],
31
[-1, 0],
32
[1, 0],
33
];
34
while (step >= 10 ** -5) {
35
const dist = calcDist(x, y);
36
let found = false;
37
for (const [xDiff, yDiff] of dirs) {
38
const newX = x + xDiff * step;
39
const newY = y + yDiff * step;
40
const newDist = calcDist(newX, newY);
41

42
// console.log(x, y, newDist, dist);
43
if (newDist < dist) {
44
x = newX;
45
y = newY;
46
found = true;
47
break;
48
}
49
}
50

51
if (!found) {
52
step /= 2;
53
}
54
}
55

56
return calcDist(x, y);
57

58
function calcDist(x, y) {
59
let dist = 0;
60
for (const [posX, posY] of positions) {
61
dist += Math.sqrt((x - posX) ** 2 + (y - posY) ** 2);
62
}
63
return dist;
64
}
65
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0