在 JavaScript 中查找最终的移动方向

javascriptweb developmentfront end technology

问题

我们需要编写一个 JavaScript 函数,该函数将单个字符数组 arr 作为第一个也是唯一的参数。

该数组只能包含 4 个字符,它们是 −

  • ‘N’ → 代表北方向
  • ‘S’ → 代表南方向
  • ‘W’ → 代表西方向
  • ‘E’ → 代表东方向

每个字符指定在该特定方向上移动的单位距离。如果数组中的任意位置有两个相反的方向 [(‘S’ 和 ‘N’) 或 (‘E’ 和 ‘W’)] 相邻出现,则它们会相互抵消移动。因此,我们的函数应该找到整个数组最终的移动方向。

例如,如果函数的输入是 −

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

那么输出应该是 −

const output = 'W';

输出解释

‘N’ 和 ‘S’ 会相互抵消 ‘E’ 和 ‘W’ 会相互抵消,最后 ‘N’ 和 ‘S’ 又会相互抵消,只留下 ‘W’。

示例

以下是代码 −

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));

输出

以下是控制台输出 −

['W']

相关文章