Finding state after all collisions in JavaScript


Problem

We are required to write a JavaScript function that takes in an array, arr, that represents the positions of different asteroids in a one-dimensional space.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Our function is supposed to find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

For example, if the input to the function is

Input

const arr = [7, 12, -8];

Output

const output = [7, 12];

Output Explanation

The 12 and -8 will collide resulting in 12.

The 7 and 12 will never collide.

Example

Following is the code −

 Live Demo

const arr = [7, 12, -8];
const findState = (arr = []) => {
   const track = []
   for (const el of arr) {
      track.push(el)
      while (track[track.length - 1] < 0 && track[track.length - 2] > 0) {
         const a = -track.pop()
         const b = track.pop()
         if (a > b) {
            track.push(-a)
         } else if (a < b) {
            track.push(b)
         }
      }
   }
   return track
};
console.log(findState(arr));

Output

[7, 12]

Updated on: 24-Apr-2021

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements