주녘공부일지

[프로그래머스 C#] Lv.1 개인정보 수집 유효기간 본문

Programmers - C#/CodingTest Lv.1

[프로그래머스 C#] Lv.1 개인정보 수집 유효기간

주녘 2024. 2. 13. 18:50
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/150370

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 정답코드 및 핵심 아이디어, 유의사항

주어진 조건에 따라 파기해야 하는 데이터의 번호를 찾는 문제

 

1) 파기해야하는 날짜는 약관의 종류에 따라 정해짐

- 딕셔너리를 활용하고 날짜 데이터 클래스에 유효 기간을 더하는 메서드 선언함

 

2) 각각에 대한 현재날짜와 파기날짜를 비교해 파기해야 하는 데이터인지 판단

- 각 날짜 데이터에 대해서 파기해야 하는 데이터인지 판단하는 메서드를 선언함

 

주석 참조

    using System;
    using System.Collections.Generic;

    public class Solution
    {
        // 날짜에 대한 데이터
        public class DataClass
        {
            public int year;
            public int month;
            public int date;

            // xxxx.xx.xx 꼴로 날짜를 넘겨받음
            public DataClass(string days)
            {
                string[] strs = days.Split('.');
                year = int.Parse(strs[0]);
                month = int.Parse(strs[1]);
                date = int.Parse(strs[2]);
            }

            // 날짜에 유효기간을 더하는 메서드
            public void AddMonth(int addMonth)
            {
                month += addMonth;
                while (month > 12)
                {
                    month -= 12;
                    year += 1;
                }
            }
        }

        public int[] solution(string today, string[] terms, string[] privacies)
        {
            var answerList = new List<int>();
            var dict = new Dictionary<char, int>(); // <약관 종류, 유효 기간>
            DataClass todays = new DataClass(today); // 오늘 날짜에 대한 데이터

            // 약관 종류에 따라 사전 세팅
            foreach (string str in terms)
            {
                string[] strs = str.Split(' ');
                dict.Add(strs[0][0], int.Parse(strs[1]));
            }

            for (int i = 0; i < privacies.Length; i++)
            {
                string[] strs = privacies[i].Split(' ');

                // 파기해야 하는 날짜 파악
                DataClass dataClass = new DataClass(strs[0]);
                dataClass.AddMonth(dict[strs[1][0]]);

                // 만약 파기해야 하는 데이터라면 번호 기록
                if (Function(todays, dataClass))
                    answerList.Add(i + 1);
            }

            return answerList.ToArray();
        }

        // 파기해야하는 날짜가 지났는지 판단하는 메서드 (현재날짜 d1, 파기날짜 d2)
        public bool Function(DataClass d1, DataClass d2)
        {
            if (d1.year != d2.year) return d1.year > d2.year;
            if (d1.month != d2.month) return d1.month > d2.month;
            return d1.date >= d2.date; // 정해진 날짜'까지' 보관이 가능함
        }
    }
728x90