Light Blue Pointer
본문 바로가기
Coding Test

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

by Greedy 2023. 12. 18.

문제 주소

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

 

프로그래머스

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

programmers.co.kr

문제 설명

고객의 약관 동의를 얻어서 수집된 1~n번으로 분류되는 개인정보 n개가 있습니다. 약관 종류는 여러 가지 있으며 각 약관마다 개인정보 보관 유효기간이 정해져 있습니다. 당신은 각 개인정보가 어떤 약관으로 수집됐는지 알고 있습니다. 수집된 개인정보는 유효기간 전까지만 보관 가능하며, 유효기간이 지났다면 반드시 파기해야 합니다.

예를 들어, A라는 약관의 유효기간이 12 달이고, 2021년 1월 5일에 수집된 개인정보가 A약관으로 수집되었다면 해당 개인정보는 2022년 1월 4일까지 보관 가능하며 2022년 1월 5일부터 파기해야 할 개인정보입니다.

당신은 오늘 날짜로 파기해야 할 개인정보 번호들을 구하려 합니다.

모든 달은 28일까지 있다고 가정합니다.

다음은 오늘 날짜가 2022.05.19일 때의 예시입니다.

약관 종류 유효기간

A 6 달
B 12 달
C 3 달

번호 개인정보 수집 일자 약관 종류

1 2021.05.02 A
2 2021.07.01 B
3 2022.02.19 C
4 2022.02.20 C
  • 첫 번째 개인정보는 A약관에 의해 2021년 11월 1일까지 보관 가능하며, 유효기간이 지났으므로 파기해야 할 개인정보입니다.
  • 두 번째 개인정보는 B약관에 의해 2022년 6월 28일까지 보관 가능하며, 유효기간이 지나지 않았으므로 아직 보관 가능합니다.
  • 세 번째 개인정보는 C약관에 의해 2022년 5월 18일까지 보관 가능하며, 유효기간이 지났으므로 파기해야 할 개인정보입니다.
  • 네 번째 개인정보는 C약관에 의해 2022년 5월 19일까지 보관 가능하며, 유효기간이 지나지 않았으므로 아직 보관 가능합니다.

따라서 파기해야 할 개인정보 번호는 [1, 3]입니다.

오늘 날짜를 의미하는 문자열 today, 약관의 유효기간을 담은 1차원 문자열 배열 terms와 수집된 개인정보의 정보를 담은 1차원 문자열 배열 privacies가 매개변수로 주어집니다. 이때 파기해야 할 개인정보의 번호를 오름차순으로 1차원 정수 배열에 담아 return 하도록 solution 함수를 완성해 주세요.


제한사항

  • today는 "YYYY.MM.DD" 형태로 오늘 날짜를 나타냅니다.
  • 1 ≤ terms의 길이 ≤ 20
    • terms의 원소는 "약관 종류 유효기간" 형태의 약관 종류와 유효기간을 공백 하나로 구분한 문자열입니다.
    • 약관 종류는 A~Z중 알파벳 대문자 하나이며, terms 배열에서 약관 종류는 중복되지 않습니다.
    • 유효기간은 개인정보를 보관할 수 있는 달 수를 나타내는 정수이며, 1 이상 100 이하입니다.
  • 1 ≤ privacies의 길이 ≤ 100
    • privacies[i]는 i+1번 개인정보의 수집 일자와 약관 종류를 나타냅니다.
    • privacies의 원소는 "날짜 약관 종류" 형태의 날짜와 약관 종류를 공백 하나로 구분한 문자열입니다.
    • 날짜는 "YYYY.MM.DD" 형태의 개인정보가 수집된 날짜를 나타내며, today 이전의 날짜만 주어집니다.
    • privacies의 약관 종류는 항상 terms에 나타난 약관 종류만 주어집니다.
  • today와 privacies에 등장하는 날짜의 YYYY는 연도, MM은 월, DD는 일을 나타내며 점(.) 하나로 구분되어 있습니다.
    • 2000 ≤ YYYY ≤ 2022
    • 1 ≤ MM ≤ 12
    • MM이 한 자릿수인 경우 앞에 0이 붙습니다.
    • 1 ≤ DD ≤ 28
    • DD가 한 자릿수인 경우 앞에 0이 붙습니다.
  • 파기해야 할 개인정보가 하나 이상 존재하는 입력만 주어집니다.
  • 파기해야 할 개인정보가 하나 이상 존재하는 입력만 주어집니다.

  • 입출력 예 
    today terms  privacies  result
    "2022.05.19" ["A 6", "B 12", "C 3"] ["2021.05.02 A", "2021.07.01 B", "2022.02.19 C", "2022.02.20 C"] [1, 3]
    "2020.01.01" ["Z 3", "D 5"] ["2019.01.01 D", "2019.11.15 Z", "2019.08.02 D", "2019.07.01 D", "2018.12.28 Z"] [1, 4, 5]

    입출력 예 설명
    • 문제 예시와 같습니다.
    입출력 예 #2약관 종류 유효기간
    Z 3 달
    D 5 달
    번호 개인정보 수집 일자 약관 종류
    1 2019.01.01 D
    2 2019.11.15 Z
    3 2019.08.02 D
    4 2019.07.01 D
    5 2018.12.28 Z
    오늘 날짜는 2020년 1월 1일입니다.
    • 첫 번째 개인정보는 D약관에 의해 2019년 5월 28일까지 보관 가능하며, 유효기간이 지났으므로 파기해야 할 개인정보입니다.
    • 두 번째 개인정보는 Z약관에 의해 2020년 2월 14일까지 보관 가능하며, 유효기간이 지나지 않았으므로 아직 보관 가능합니다.
    • 세 번째 개인정보는 D약관에 의해 2020년 1월 1일까지 보관 가능하며, 유효기간이 지나지 않았으므로 아직 보관 가능합니다.
    • 네 번째 개인정보는 D약관에 의해 2019년 11월 28일까지 보관 가능하며, 유효기간이 지났으므로 파기해야 할 개인정보입니다.
    • 다섯 번째 개인정보는 Z약관에 의해 2019년 3월 27일까지 보관 가능하며, 유효기간이 지났으므로 파기해야 할 개인정보입니다.

풀이과정

⭐Java String split

Public String [] split ( String regex, int limit)

  • limit > 0 – If this is the case, then the pattern will be applied at most limit-1 times, the resulting array’s length will not be more than n, and the resulting array’s last entry will contain all input beyond the last matched pattern.
  • limit < 0 – In this case, the pattern will be applied as many times as possible, and the resulting array can be of any size.
  • limit = 0 – In this case, the pattern will be applied as many times as possible, the resulting array can be of any size, and trailing empty strings will be discarded.
Regex Limit Result
@ 2 {“geekss”, ”for@geekss”}
@ 5 {“geekss”, ”for”, ”geekss”}
@ -2 {“geekss”, ”for”, ”geekss”}
s 5 {“geek”, ”“, “@for@geek”, “”, “”}
s -2 {“geek”, ” “, ” “, “@for@geek”, “”, “”}
s 0 {“geek”, ””, ”@for@geek”}

today를 쪼개기 위해서 찾아봄

import java.util.HashMap;
import java.util.ArrayList;

class Solution {
    public int[] solution(String today, String[] terms, String[] privacies) {
        
        
        
        String [] toDay = today.split(".");
        ArrayList<Integer> delete = new ArrayList<Integer>();
        HashMap<String,Integer> term = new HashMap<String,Integer>();
        
        for(int i=0; i<terms.length; i++){
            String [] temp = terms[i].split(" ");
            term.put(temp[0],Integer.parseInt(temp[1]));    
        }
        
        for(int i=0; i<privacies.length; i++){
            String [] temp = privacies[i].split(" ");//temp[1]==약관 종류
            String [] theday = temp[0].split(".");
            
            int span = term.get(temp[1])*28;
            
            int years = Integer.parseInt(toDay[0])-Integer.parseInt(theday[0]);
            int months = (years*12)+Integer.parseInt(toDay[1])-Integer.parseInt(theday[1]);
            int days = (months*28)+Integer.parseInt(toDay[2])-Integer.parseInt(theday[2]);
            
            if(span-days<0){
                delete.add(i);
            }  
        }
        
        int[] answer = new int[delete.size()];
        
        for(int i=0;i<delete.size(); i++){
            answer[i] = delete.get(i);
        }

        return answer;
    }
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

at Solution.solution(Unknown Source)

at SolutionTest.lambda$main$0(Unknown Source)

at SolutionTest$SolutionRunner.run(Unknown Source)

at SolutionTest.main(Unknown Source)

→ 어디에서 났을까?

봐도 모르겠는데…

ArrayIndexOutOfBoundsException

split으로 쪼갠거 읽다가 났을듯…

//         for(int i=0; i<privacies.length; i++){
//             String [] temp = privacies[i].split(" ");//temp[1]==약관 종류,temp[0] 계약 날짜
//             String [] theday = temp[0].split(".");
            
//             int span = term.get(temp[1])*28;
            
//             int years = Integer.parseInt(toDay[0])-Integer.parseInt(theday[0]);
//             int months = (years*12)+Integer.parseInt(toDay[1])-Integer.parseInt(theday[1]);
//             int days = (months*28)+Integer.parseInt(toDay[2])-Integer.parseInt(theday[2]);
            
//             if(span-days<0){
//                 delete.add(i);
//             }  
//         }

주석처리해보니까 여기에서 저 에러가 난거였음

int years = Integer.parseInt(toDay[0])-Integer.parseInt(theday[0]);

이 문장 주석 풀면 런타임 에러남

0이 toDay게 안 들어갔을까 theday 게 안들어갔을까

int years = /*Integer.parseInt(toDay[0])-*/Integer.parseInt(theday[0]); //→ 에러남

int years = Integer.parseInt(toDay[0])/*Integer.parseInt(theday[0])*/; //→ 에러남

두개 다 안 들어갔나봄 ㅎㅎ

for(int i=0; i<privacies.length; i++){
            String [] temp = privacies[i].split(" ");//temp[1]==약관 종류,temp[0] 계약 날짜
            System.out.println(temp[0]);
            String [] theday = temp[0].split(".");
            
            
            int span = term.get(temp[1])*28;

로그 찍어보면 temp[0]은 똑바로 됐음

String [] temp = privacies[i].split(" ");//temp[1]==약관 종류,temp[0] 계약 날짜
            System.out.println(temp[0]);
            String [] theday = temp[0].split(".");
            System.out.println(theday[0]); -> 에러남

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

at Solution.solution(Unknown Source)

at SolutionTest.lambda$main$0(Unknown Source)

at SolutionTest$SolutionRunner.run(Unknown Source)

at SolutionTest.main(Unknown Source)

왜 “.” 으로는 split이 안 되는지 구글링해봄

The split() method in Java does not work on a dot (.) [duplicate]

553

[java.lang.String.split](<http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String->) splits on regular expressions, and . in a regular expression means "any character".

Try temp.split("\\.").

⭐Java Split dot(".") -> ("\\.")

for(int i=0; i<privacies.length; i++){
            String [] temp = privacies[i].split(" ");//temp[1]==약관 종류,temp[0] 계약 날짜
            System.out.println(temp[0]);
            String [] theday = temp[0].split("\\\\.");
            System.out.println(theday[0]);
            
            int span = term.get(temp[1])*28;

오 고치니까 됨

출력 〉	
2021.05.02
2021
2021.07.01
2021
2022.02.19
2022
2022.02.20
2022
import java.util.HashMap;
import java.util.ArrayList;

class Solution {
    public int[] solution(String today, String[] terms, String[] privacies) {
        
        
        
        String [] toDay = today.split("\\\\.");
        ArrayList<Integer> delete = new ArrayList<Integer>();
        HashMap<String,Integer> term = new HashMap<String,Integer>();
        
        for(int i=0; i<terms.length; i++){
            String [] temp = terms[i].split(" ");
            term.put(temp[0],Integer.parseInt(temp[1]));    
        }
        
        for(int i=0; i<privacies.length; i++){
            String [] temp = privacies[i].split(" ");//temp[1]==약관 종류,temp[0] 계약 날짜
            String [] theday = temp[0].split("\\\\.");
            
            int span = term.get(temp[1])*28;
            
            int years = Integer.parseInt(toDay[0])-Integer.parseInt(theday[0]);
            int months = (years*12)+Integer.parseInt(toDay[1])-Integer.parseInt(theday[1]);
            int days = (months*28)+Integer.parseInt(toDay[2])-Integer.parseInt(theday[2]);
            
             if(span-days<0){
                 delete.add(i);
             }  
        }
        
        int[] answer = new int[delete.size()];
        
        for(int i=0;i<delete.size(); i++){
            answer[i] = delete.get(i);
        }

        return answer;
    }
}

이제 런타임 오류는 안 난다

테스트 1
입력값 〉	"2022.05.19", ["A 6", "B 12", "C 3"], ["2021.05.02 A", "2021.07.01 B", "2022.02.19 C", "2022.02.20 C"]
기댓값 〉	[1, 3]
실행 결과 〉	실행한 결괏값 [0]이 기댓값 [1,3]과 다릅니다.
테스트 2
입력값 〉	"2020.01.01", ["Z 3", "D 5"], ["2019.01.01 D", "2019.11.15 Z", "2019.08.02 D", "2019.07.01 D", "2018.12.28 Z"]
기댓값 〉	[1, 4, 5]
실행 결과 〉	실행한 결괏값 [0,3,4]이 기댓값 [1,4,5]과 다릅니다.

보니까 인덱스를 그대로 넣으면 안 되고 1 더해서 넣어줘야 되고

날짜 뺀거에 1 더해줘야 돼서

이 코드 수정함

if(span-days<0){ -> if(span-days<=0){
                 delete.add(i); -> delete.add(i+1);
             }

그리고 통과했다!

 

제출 코드

import java.util.HashMap;
import java.util.ArrayList;

class Solution {
    public int[] solution(String today, String[] terms, String[] privacies) {
        
        
        
        String [] toDay = today.split("\\\\.");
        ArrayList<Integer> delete = new ArrayList<Integer>();
        HashMap<String,Integer> term = new HashMap<String,Integer>();
        
        for(int i=0; i<terms.length; i++){
            String [] temp = terms[i].split(" ");
            term.put(temp[0],Integer.parseInt(temp[1]));    
        }
        
        for(int i=0; i<privacies.length; i++){
            String [] temp = privacies[i].split(" ");//temp[1]==약관 종류,temp[0] 계약 날짜
            String [] theday = temp[0].split("\\\\.");
            
            int span = term.get(temp[1])*28;
            
            int years = Integer.parseInt(toDay[0])-Integer.parseInt(theday[0]);
            int months = (years*12)+Integer.parseInt(toDay[1])-Integer.parseInt(theday[1]);
            int days = (months*28)+Integer.parseInt(toDay[2])-Integer.parseInt(theday[2]);
            
             if(span-days<=0){
                 delete.add(i+1);
             }  
        }
        
        int[] answer = new int[delete.size()];
        
        for(int i=0;i<delete.size(); i++){
            answer[i] = delete.get(i);
        }

        return answer;
    }
}