Skip to content

Commit f3f9cbf

Browse files
authored
Create 1515-best-position-for-a-service-centre.js
1 parent e5a95a4 commit f3f9cbf

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @param {number[][]} positions
3+
* @return {number}
4+
*/
5+
const getMinDistSum = function(positions) {
6+
const n = positions.length
7+
let x = positions.reduce((ac, e) => ac + e[0], 0) / n
8+
let y = positions.reduce((ac, e) => ac + e[1], 0) / n
9+
10+
const dirs = [[1,0],[-1,0],[0,1],[0,-1]]
11+
let res = fn(x, y, positions)
12+
let chg = 100
13+
while(chg > 1e-6) {
14+
let zoom = true
15+
for(let [dx, dy] of dirs) {
16+
const nx = x + dx * chg
17+
const ny = y + dy * chg
18+
const nRes = fn(nx, ny, positions)
19+
if(nRes < res) {
20+
res = nRes
21+
x = nx
22+
y = ny
23+
zoom = false
24+
break
25+
}
26+
}
27+
if(zoom) chg /= 2
28+
}
29+
return res
30+
};
31+
32+
function fn(x, y, arr) {
33+
let res = 0
34+
const n = arr.length
35+
for(let i = 0; i < n; i++) {
36+
res += Math.sqrt((x - arr[i][0]) ** 2 + (y - arr[i][1]) ** 2)
37+
}
38+
return res
39+
}

0 commit comments

Comments
 (0)