Search for a command to run...
Try your own input
Change the array and replay the algorithm from step one.
Initialization
Repeatedly sweep the row looking for an adjacent pair that collides (▶ then ◀). Resolve that one collision, then start over, until a full sweep finds nothing left to resolve.
Brute Force
1function asteroidCollision(asteroids) {2 const arr = [...asteroids];3 let changed = true;//asteroids: [5, 10, -5, -20, 8, -8]4 while (changed) {5 changed = false;6 for (let i = 0; i + 1 < arr.length; i++) {7 if (arr[i] > 0 && arr[i + 1] < 0) {8 if (arr[i] < -arr[i + 1]) arr.splice(i, 1);9 else if (arr[i] > -arr[i + 1]) arr.splice(i + 1, 1);10 else arr.splice(i, 2);11 changed = true;12 break;13 }14 }15 }16 return arr;17}