Kata Practice - Growth of a Population (JavaScript)

Kata Practice - Growth of a Population (JavaScript)

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

題目

In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater than or equal to p = 1200 inhabitants?

1
2
3
4
5
6
7
8
9
10
At the end of the first year there will be: 
1000 + 1000 * 0.02 + 50 => 1070 inhabitants

At the end of the 2nd year there will be:
1070 + 1070 * 0.02 + 50 => 1141 inhabitants (** number of inhabitants is an integer **)

At the end of the 3rd year there will be:
1141 + 1141 * 0.02 + 50 => 1213

It will need 3 entire years.

More generally given parameters:

p0, percent, aug (inhabitants coming or leaving each year), p (population to equal or surpass)

the function nb_year should return n number of entire years needed to get a population greater or equal to p.

aug is an integer, percent a positive or null floating number, p0 and p are positive integers (> 0)

自己的解法

1
2
3
4
5
6
7
8
9
10
const nbYear = (p0, percent, aug, p) => {
let calculateValue = p0 + p0*(percent/100) + aug
let years = 1
while (calculateValue < p) {
let recalculateValue = calculateValue + calculateValue*(percent/100) + aug
calculateValue = Math.floor(recalculateValue)
years++
}
return years
}

解題脈絡

當下先想到了 for 迴圈的方法,但不確定要怎麼設定執行次數,所以改成使用 while 這個方法。最後設定新的人口數 calculateValue 和幾年的時間 years 的變數來儲存目前的值,最後當 calculateValue 的人數超過 p 參數的時候,就可以返回 years 的值了。

其他人的解法

1
2
3
4
5
6
function nbYear(p0, percent, aug, p) {
for (var years = 0; p0 < p; years++) {
p0 = Math.floor(p0 + p0 * percent / 100 + aug);
}
return years
}

選擇記錄這個解法的原因

雖然有想到使用 for 迴圈,不過當時不知道可以直接使用 p0 參數就好,並不需要自己再多設定一個變數。
最後再將本來的 p0 變數更新成最新的值,這樣就可以直接判斷目前的人口有沒有達到 p 的值了。
不過下面有一些人回覆說,重新將參數賦予值並不是一個好的作法,所以就看大家實際怎麼解決這個問題囉。

觀念釐清

好像是第一次靠自己的解法(沒有查 ChatGPT 或是其他 AI 服務)就自己寫出來的 7kyu 等級題目,感覺題目不難,但是思考的時間跟 8kyu 的題目比起來確實要多花一點時間。
當然也有可能是我自己還不夠熟哈哈,所以才要多多練習呢!

那我們就下次見ʘ‿ʘ

評論