Đề bài
Viết hàm nhận mảng ký tự chỉ chứa 'N','S','W','E' (Bắc, Nam, Tây, Đông). Mỗi ký tự là một bước đơn vị. Hai hướng ngược nhau xuất hiện liền kề ('NS','SN','EW','WE') sẽ triệt tiêu nhau. Tìm hướng còn lại sau khi triệt tiêu hết cặp.
Ví dụ: ['N','S','S','E','W','N','W'] → ['W'].
Ví dụ
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']
Kết quả
['W']