Finding the final direction of movement in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of single characters, arr, as the first and the only argument.

The array can contain of only 4 characters, they are −

  • ‘N’ → stands for North direction
  • ‘S’ → stands for South direction
  • ‘W’ → stands for West direction
  • ‘E’ → stands for East direction

Each character specifies a move of unit distance in that particular direction. And if anywhere in the array, two opposite directions, [(‘S’ and ‘N’) or (‘E’ and ‘W’)] appear adjacently, they cancel out the movement of each other. Therefore, our function is supposed to find the resulting direction of movement of the whole array.

For example, if the input to the function is −

const arr = ['N', 'S', 'S', 'E', 'W', 'N', 'W'];

Then the output should be −

const output = 'W';

Output Explanation

‘N’ and ‘S’ will cancel each other ‘E’ and ‘W’ will cancel each other and then finally ‘N’ and ‘S’ again cancels each other to leave behind only ‘W’.

Example

Following is the code −

 Live Demo

const arr = ['N', 'S', 'S', 'E', 'W', 'N', 'W'];
const cancelDirections = (arr = []) => {

   let str = arr.join('');
   while(str.includes('NS') || str.includes('SN') || str.includes('EW')
|| str.includes('WE')){
      str = str.replace('NS', '');
      str = str.replace('SN', '');
      str = str.replace('EW', '');
      str = str.replace('WE', '');
   };
   return str.split('');
};
console.log(cancelDirections(arr));

Output

Following is the console output −

['W']
raja
Published on 22-Apr-2021 09:49:50
Advertisements