https://school.programmers.co.kr/learn/courses/30/lessons/150370
function solution(today, terms, privacies) {
const [cYear, cMonth, cDay] = today.split(".").map((v)=>+v);
const termsMap = {};
terms.forEach((v)=>{
const [term, limit] = v.split(" ");
termsMap[term] = +limit;
});
const answer = [];
privacies.forEach((v, i)=>{
const [date, term] = v.split(" ");
const [year, month, day] = date.split(".").map((v)=>+v);
let limitYear = year + Math.floor(termsMap[term] / 12),
limitMonth = month + termsMap[term] % 12,
limitDay = day - 1;
if (limitMonth > 12) {
limitYear += 1;
limitMonth %= 12;
}
if (limitDay === 0) {
limitDay = 28;
limitMonth -= 1;
}
if (cYear > limitYear) {
answer.push(i + 1);
} else if (cYear === limitYear && cMonth > limitMonth) {
answer.push(i + 1);
} else if (cYear === limitYear && cMonth === limitMonth && cDay > limitDay) {
answer.push(i + 1);
}
})
return answer;
}
유효기간
을 어떻게 구해야 하는지 헷갈려서 매우매우매우 오래 걸렸고, 너무너무너무 어려웠다. ㅠㅠ 특히, limitMonth
와 limitYear
를 구하는 과정에서 term
의 개월만 계산하면 되는 것을, 계속 month
와 더한 값으로 계산한 탓에 많이 헤맸다.
만약 termsMap[term]
이 100
이고 month
가 8
일 때, limitYear
에 year + Math.floor((month + termsMap[term]) / 12)
로, limitMonth
는 (month + termsMap[term]) % 12
로 계산했다. 그러면 전자에는 9
를 더하고, 후자는 0
이 된다. 100
개월 후이기 때문에 year
에 8
을 더했어야 함에도 말이다.
limitYear
와 limitMonth
는 termsMap[term]
으로만 계산하면 됨을 깨닫고 다시 할당했다. termsMap[term] / 12
는 유효 연수, termsMap[term] % 12
는 유효 개월 수다. 신경 써야 할 부분은 limitMonth
가 12
를 넘는 경우로, 한 해가 넘어가기 때문에 limitYear
에 1
을 더하고, limitMonth
는 다시 12
로 나눈 나머지를 재할당했다.
limitDay
는 현재보다 하루 전까지이므로 day - 1
을 했는데, 값이 0
인 경우 전달 마지막일이어서 limitMonth
에서 1
을 뺐다.
풀고 보니 단순 계산 문제였다. 수학 공부 좀 해야겠다...