在 JavaScript 中尋找最終的移動方向


問題

我們需要編寫一個 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']

更新於: 22-Apr-2021

269 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.