Kata Practice - Number of People in the Bus (JavaScript)

Kata Practice - Number of People in the Bus (JavaScript)

這個系列會把自己練習過的 Kata 題目記錄下來,希望除了記錄的性質以外也能夠觀察自己撰寫程式邏輯的進化過程。如果有幸看到這邊的話也可以參考一下,再到 Codewars 的網站註冊一個帳號試著玩看看,自己蠻喜歡整個網站的得分和排行榜設定,會讓人越寫越有成就感喔!

題目

There is a bus moving in the city which takes and drops some people at each bus stop.

You are provided with a list (or array) of integer pairs. Elements of each pair represent the number of people that get on the bus (the first item) and the number of people that get off the bus (the second item) at a bus stop.

Your task is to return the number of people who are still on the bus after the last bus stop (after the last array). Even though it is the last bus stop, the bus might not be empty and some people might still be inside the bus, they are probably sleeping there :D

Take a look on the test cases.

Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the returned integer can’t be negative.

The second value in the first pair in the array is 0, since the bus is empty in the first bus stop.

自己的解法

1
2
3
4
5
6
7
8
const number = (busStops) => {
const countPeople = busStops.map((item)=>{
return item[0]-item[1]
})
return countPeople.reduce((acc, cur) => {
return acc + cur
},0);
}

解題脈絡

第一個念頭就是先把每一個陣列裡面的陣列都遍歷一次,先將每一次的上下車數量做計算,最後再使用 reduce 的方法做全部的加總。

其他人的解法

1
const number = (busStops) => busStops.reduce((rem, [on, off]) => rem + on - off, 0);

選擇記錄這個解法的原因

看了這個解法之後發現自己又多做了一個步驟,加上可能對 reduce 的用法也不夠熟,所以才先使用 map 來處理每一次的上下車人數,但其實 reduce 就可以針對當前的值去做額外的處理了。

觀念釐清

雖然多了一個步驟,但我覺得以我目前的程度來說我比較希望自己可以先在自己的腦袋裡想執行方法,最後真的記不得語法的話再去 google 搜尋。
不過這樣練下來之後發現自己已經可以先把要處理的方式跟要使用到的陣列 function 都先想好了,是個很顯著的進步!

那我們就下次見ʘ‿ʘ

評論