[JS] 프로그래머스 Lv1 - 개인정보 수집 유효기간

찐새·2023년 5월 15일
0

코딩테스트

목록 보기
44/53
post-thumbnail

개인정보 수집 유효기간

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;
}

풀이

유효기간을 어떻게 구해야 하는지 헷갈려서 매우매우매우 오래 걸렸고, 너무너무너무 어려웠다. ㅠㅠ 특히, limitMonthlimitYear를 구하는 과정에서 term의 개월만 계산하면 되는 것을, 계속 month와 더한 값으로 계산한 탓에 많이 헤맸다.

만약 termsMap[term]100이고 month8일 때, limitYearyear + Math.floor((month + termsMap[term]) / 12)로, limitMonth(month + termsMap[term]) % 12로 계산했다. 그러면 전자에는 9를 더하고, 후자는 0이 된다. 100개월 후이기 때문에 year8을 더했어야 함에도 말이다.

limitYearlimitMonthtermsMap[term]으로만 계산하면 됨을 깨닫고 다시 할당했다. termsMap[term] / 12는 유효 연수, termsMap[term] % 12는 유효 개월 수다. 신경 써야 할 부분은 limitMonth12를 넘는 경우로, 한 해가 넘어가기 때문에 limitYear1을 더하고, limitMonth는 다시 12로 나눈 나머지를 재할당했다.

limitDay는 현재보다 하루 전까지이므로 day - 1을 했는데, 값이 0인 경우 전달 마지막일이어서 limitMonth에서 1을 뺐다.

느낀점

풀고 보니 단순 계산 문제였다. 수학 공부 좀 해야겠다...

profile
프론트엔드 개발자가 되고 싶다

0개의 댓글