Codewars: Directions Reduction

Kion
6 min readApr 25, 2019

--

學習重點: reduce()

題目連結

題目摘要

The directions given to the man are, for example, the following:

["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"].

You can immediately see that going “NORTH” and then “SOUTH” is not reasonable, better stay in the same place! So the task is to give to the man a simplified version of the plan. A better plan, in this case, is simply:

["WEST"]

從題目敘述可以明白:

題目會給一段:東西南北,隨機組合的字串
南北、東西,為相反值,又要走南又要走北其實停留在原地就好了,大可直接刪除
目標是:輸出最後沒有被抵消的字串

題目做法

  1. 我的作法
if & for 迴圈
if & while 迴圈

2. 大神作法

物件 & reduce( ) method

看不懂 plan.reduce()??先解釋一下 reduce( ) method 是怎麼運作

reduce 是將陣列中每項元素(由左至右)傳入 callback 函式,將陣列化為單一值的方法

arr.reduce(
function(accumulator, currentValue, currentIndex, array){
...
}, initialValue)

callback 函式可傳入的參數分為以下四種:

  1. accumulater 累加器變數名稱或是 initialValue (required)
    類似:
    accumulater += currentValue; 的概念
    原陣列的第一個元素將會被當作初始的累加器,因此假如空陣列呼叫 reduce() 方法且沒有提供累加器初始值,將會發生錯誤
    但如果 initialValue 有給值,accumulater 就是的初始值就是 initialValue
  2. currentValue 原陣列目前迭代處理的元素變數名稱 (required)
  3. currentIndex 原陣列目前迭代處理的元素索引值變數名稱 (optional)
    若有傳入 initialValue,則由索引 0 的元素開始
    若無傳入 initialValue,第一個元素已被當作初始的累加器,因此是從索引 1 的元素開始
  4. array 呼叫 reduce () 的陣列變數名稱 (optional)

另外,

  1. initialValue 要傳入的累加器初始值 (optional)
    影響 accumulater 的初始值,以及迭代處理的元素,索引 0 到底會不會被 callback 函式處理到

回頭看程式碼:

reduce( )

三、混合做法

物件 & while

為什麼要 while(i < arr.length — 1) 呢?

透過 console.log 觀察迴圈的次數可以發現:

有 -1

速度:722ms

var arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"];
var correspond = {
"NORTH": "SOUTH",
"SOUTH": "NORTH",
"EAST": "WEST",
"WEST": "EAST",
};
var i = 0;
while (i < arr.length-1) {
if (correspond[arr[i]] == arr[i + 1]) {
arr.splice(i, 2);
console.log(i);
i--;
} else {
console.log(i);
i++;
}
}

輸出結果:

VM69:12 0
VM69:15 -1
VM69:15 0
VM69:12 1
VM69:12 0
VM69:15 -1

沒有 -1

速度:12000ms

var arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"];
var correspond = {
"NORTH": "SOUTH",
"SOUTH": "NORTH",
"EAST": "WEST",
"WEST": "EAST",
};
var i = 0;
while (i < arr.length) {
if (correspond[arr[i]] == arr[i + 1]) {
arr.splice(i, 2);
console.log(i);
i--;
} else {
console.log(i);
i++;
}
}

輸出結果:

VM72:12 0
VM72:15 -1
VM72:15 0
VM72:12 1
VM72:12 0
VM72:15 -1
VM72:15 0

沒有-1 的迴圈多了一次
且在效能上,沒有-1 的速度比 有-1 的快很多

拍個手讓我知道,這個文章對你們有幫助 ♥(´∀` )人

--

--

Kion
Kion

Written by Kion

程式就是利用自動化與排程的特性解決問題 文章分類總覽: https://hackmd.io/@Kion/SyvyEks0L

No responses yet