Skip to content

Commit a852473

Browse files
authored
Create 2751-robot-collisions.js
1 parent 9ace233 commit a852473

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

2751-robot-collisions.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {number[]} positions
3+
* @param {number[]} healths
4+
* @param {string} directions
5+
* @return {number[]}
6+
*/
7+
const survivedRobotsHealths = function (positions, healths, directions) {
8+
const p = positions,
9+
h = healths,
10+
d = directions
11+
let m = {},
12+
res = Array(p.length).fill(0)
13+
p.map((x, i) => (m[x] = d[i] == 'R' ? [h[i], i] : [-h[i], i]))
14+
let a = []
15+
for (const k in m) a.push(m[k])
16+
let v = asteroidCollision(a)
17+
for (const [x, i] of v) res[i] = Math.abs(x)
18+
return res.filter((x) => x != 0)
19+
}
20+
21+
function asteroidCollision(a) {
22+
let st = []
23+
for (const [x, i] of a) {
24+
st.push([x, i])
25+
let l, li, sl, sli
26+
if (st.length >= 1) [l, li] = st[st.length - 1]
27+
if (st.length >= 2) [sl, sli] = st[st.length - 2]
28+
while (st.length >= 2 && l < 0 && sl > 0) {
29+
st.pop()
30+
st.pop()
31+
let add, idx
32+
if (-l > sl) {
33+
add = -(-l - 1)
34+
idx = li
35+
} else if (-l < sl) {
36+
add = sl - 1
37+
idx = sli
38+
}
39+
if (add) st.push([add, idx])
40+
if (st.length >= 1) [l, li] = st[st.length - 1]
41+
if (st.length >= 2) [sl, sli] = st[st.length - 2]
42+
}
43+
}
44+
return st
45+
}

0 commit comments

Comments
 (0)