https://www.codewars.com/kata/563b662a59afc2b5120000c6
Codewars - Achieve mastery through coding practice and developer mentorship
A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!
www.codewars.com
DESCRIPTION:
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 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)
Examples:
nb_year(1500, 5, 100, 5000) -> 15
nb_year(1500000, 2.5, 10000, 2000000) -> 10
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.
설명:
작은 마을의 인구는 첫해에 p0 = 1000입니다. 인구는 매년 정기적으로 2퍼센트씩 증가하고 매년 50명 이상의 새로운 주민이 마을에 살게 됩니다. 마을의 인구가 p = 1200 이상이 되려면 몇 년이 필요한가요?
첫해 말은 다음과 같습니다:
1000 + 1000 * 0.02 + 50 => 1070 주민
두번째 해의 말은 다음과 같습니다:
1070 + 1070 * 0.02 + 50 => 1141 주민 (** 주민의 수는 정수입니다 **)
세번째 해의 말은 다음과 같습니다:
1141 + 1141 * 0.02 + 50 => 1213
총 3년이 필요합니다.
일반적으로 주어진 매개변수:
p0, percent, aug (매년 들어오거나 나가는 인구수), p (같거나 초과하는 인구)
함수 nb_year는 인구가 p 이상의 인구를 얻는데 필요한 전체 연도 n을 반환해야 합니다.
aug는 정수, percent는 정수 또는 널 부동 숫자, p0과 p는 양의 정수입니다(> 0).
예:
nb_year(1500, 5, 100, 5000) -> 15
nb_year(1500000, 2.5, 10000, 2000000) -> 10
참고:
percent 매개변수를 함수 안에서 백분율로 바꾸는 것을 잊지 마세요: 만약 percent 매개변수가 2라면 0.02로 바꿔야 합니다.
풀이
초기값 p0에 percent를 백분율로 바꾼 값을 곱하고 주민의 수는 정수여야 하기 때문에 나온 결과를 내림해서 aug와 더한 값을 다시 p0에 저장해 그 값이 p보다 작을 때까지 반복해주었고 반복문이 돌아간 횟수를 반환했다.
코드
function nbYear(p0, percent, aug, p) {
let count = 0;
while(p0 < p){
p0 += Math.floor(p0 * (percent / 100)) + aug;
count++;
}
return count;
}
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Regex validate PIN code (7 kyu) / JavaScript (0) | 2022.12.20 |
---|---|
[Codewars] Printer Errors (7 kyu) / JavaScript (0) | 2022.12.19 |
[Codewars] Find the next perfect square! (7 kyu) / JavaScript (0) | 2022.12.16 |
[Codewars] Does my number look big in this? (6 kyu) / JavaScript (0) | 2022.12.15 |
[Codewars] Equal Sides Of An Array (6 kyu) / JavaScript (0) | 2022.12.14 |
댓글