문제설명
We all love fridays, and even better if it is the last day of the month!
In this kata you should write a function that will receive 2 parameters. Both are years, and indicates a range.
Your work is to return the number of times a month ends with a Friday.
If there is only one year provided, return the number of times a month ends on Friday on that year. Range bounds are inclusive in every case!
For example, between 1901 and 2000, a month ends on Friday 101 times.
나의풀이
function lastDayIsFriday(initialYear, endYear) {
if(!endYear) endYear = initialYear;
var numOfFridays = 0;
var month = 1;
var day = ['Sun','Mon','Tue','Wed','Thur','Fri','Sat'];
var lastDate = new Date(initialYear, month, 0);
var lastDayOfMonth = day[lastDate.getDay()];
while(lastDate.getFullYear() <= endYear){
if(lastDayOfMonth === 'Fri'){
numOfFridays++;
}
month += 1;
lastDate = new Date(initialYear,month,0);
lastDayOfMonth = day[lastDate.getDay()];
}
return numOfFridays;
}다른사람의 풀이
function lastDayIsFriday(initialYear, endYear) {
let start = new Date(initialYear, 1, 0);
let end = new Date(endYear || initialYear, 11, 31);
let count = 0;
for (let i = 1; start <= end; start = new Date(initialYear,++i,0)) {
if (start.getDay() == 5) count++;
}
return count;
}
느낀점
배열은 굳이 안써도 괜찮았을 것같은데, 다시볼 때 알아보기 쉽게 하려고 썼다. 그리고 어떤부분에선 for문 보다는
while 문이 쓰기 편하기도 한듯하다. Date 객체에 (년도, 월 ,일 ) 순으로 넣을때 '일에' 0을 넣어주면 당월의 전월 마지막날을 알 수 있다. 그게 풀이의
핵심.
'algorithm > codewars' 카테고리의 다른 글
[6kyu] playing with digits (0) | 2018.01.28 |
---|---|
[6kyu] multiples of 3 or 5 (0) | 2018.01.28 |
[8kyu] Century_From_Year !!!!!!!!!! (0) | 2018.01.21 |
[6kyu] Good vs Evil (0) | 2018.01.21 |
[8kyu] Array plus array (0) | 2018.01.21 |