- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the final direction of movement in JavaScript
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 −
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']
- Related Articles
- C++ code to find reduced direction string of robot movement
- Finding the inclination of arrays in JavaScript
- Finding the balance of brackets in JavaScript
- The movement of food in food pipe is called(a) Linear movement (b) Rectilinear movement(c) Smooth movement(d) Peristaltic movement
- Finding the rotation of an array in JavaScript
- Finding the continuity of two arrays in JavaScript
- Finding the mid of an array in JavaScript
- Finding persistence of number in JavaScript
- Finding sum of multiples in JavaScript
- Finding score of brackets in JavaScript
- Finding the smallest multiple in JavaScript
- Finding the length of a JavaScript object
- Finding the intersection of arrays of strings - JavaScript
- Finding the number of words in a string JavaScript
- Finding the validity of a hex code in JavaScript
