iT邦幫忙

1

CodeWars : 新手村練等紀錄02- Growth of a Population

  • 分享至 

  • xImage
  •  

Growth of a Population

等級:7kyu

原始題目

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 or equal to p = 1200 inhabitants?

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 surpass)

the functionnb_yearshould 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)

Note:
Don't forget to convert the percent parameter as a percentage in the body of your function: if the parameter percent is 2 you have to convert it to 0.02.

Examples:
nb_year(1500, 5, 100, 5000) -> 15
nb_year(1500000, 2.5, 10000, 2000000) -> 10

中翻:
nb_year這個function要能回傳人口成長到一定數量所需的時間(單位:年)
參數共有4個

  1. p0:代表原始人口
  2. percent:表示成長數值(需要另外換算成百分比)
  3. aug:表示每年新增/減少的人口,此數值可能為正整數或負整數
  4. p:為預計成長到的人口數量

自解:

export class G964 {
    public static nbYear = (p0, percent, aug, p) => {   
        let inhabitants = p0;
        let i = 0
        while(inhabitants < p){
          inhabitants = Math.floor((1 + percent/100)* inhabitants) + aug;
          i++
        } 
        return i
    }
}

這次題目算是比較單純的在測試迴圈的撰寫,我使用的是whlie的寫法,另外有用Math.floor方法取整數(因為人口不會是小數點,但在此題應該是非必要的處理)

下方有其他人用for迴圈的寫法可以參考。

他解:

author: g964

export class G964 {
    public static nbYear = (p0, percent, aug, p) => {
        for(var y = 0; p0 < p; y++) p0 = p0 * (1 + percent / 100) + aug;
        return y;
    }
}

此次題目使用到的方法和參考網址:

Math.floor() 函式會回傳小於等於所給數字的最大整數。
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

(另外補充)Math.celi() 函式會回傳大於等於所給數字的最小整數。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil

(另外補充)Static function 突然對static function的用法和意義有點模糊,看到此題剛好去複習一下
https://medium.com/enjoy-life-enjoy-coding/typescript-%E5%BE%9E-ts-%E9%96%8B%E5%A7%8B%E5%AD%B8%E7%BF%92%E7%89%A9%E4%BB%B6%E5%B0%8E%E5%90%91-class-%E7%94%A8%E6%B3%95-20ade3ce26b8
來源: 神Q超人
此篇也順便複習整個class用法。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言