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

c4fiber·2023년 3월 19일
0

code-interview

목록 보기
6/12

요약 및 과정

  • 요약
    • string을 분리하기 위해 spiit 함수를 구현
    • 만료되었는지를 판단하기 위한 expired 함수 구현
    • 만료날짜를 구하기 위한 getEndDate 구현
  • 과정
    • split 함수를 구현해 delemiter에 따라 분리시키도록함
    • 사칙연산을 수월하게 하기위해 applyStoi 함수를 만들어 간편하게 변환시킬 수 있도록 했다.
    • compare 함수 정의를 통해 max 함수를 사용해서 간단히 비교할 수 있도록 했다.
      • operator overload를 활용하면 더 간결하게 가능할 것으로 예상한다.
    • map을 활용해서 약관의 타입별로 유효기간이 몇인지 바로 얻어서 활용할 수 있도록 했다.

구현

#include <string>
#include <vector>
#include <sstream>
#include <map>

using namespace std;

vector<string> split(string, char);
bool compare(vector<int>, vector<int>);
bool expired(string, string);
string getEndDate(string, int);
vector<int> changeStringToInt(vector<string>);

vector<string> split(string input, char delemiter) {
    stringstream ss(input);
    vector<string> splited;
    string temp;

    while(getline(ss, temp, delemiter)) {
        splited.push_back(temp);
    }

    return splited;
}

bool compare(vector<int> a, vector<int> b) {    
    if (a[0] != b[0]) 
        return a[0] < b[0];

    if (a[1] != b[1]) 
        return a[1] < b[1];

    return a[2] < b[2];
}

vector<int> applyStoi(vector<string> v) {
    vector<int> changed;
    for(string s : v) {
        changed.push_back(stoi(s));
    }

    return changed;
}

bool expired(string today, string endDate) {
    vector<int> T = applyStoi(split(today, '.'));
    vector<int> E = applyStoi(split(endDate, '.'));

    return max(T, E, compare) == T;
}

string getEndDate(string date, int duringMonth) {  
    vector<int> nums = applyStoi(split(date, '.'));

    nums[1] += duringMonth;
    while(nums[1] > 12) {
        nums[1] -= 12;
        nums[0] += 1;
    }

    return "" + to_string(nums[0]) + "." + to_string(nums[1]) + "." + to_string(nums[2]);
}

vector<int> solution(string today, vector<string> terms, vector<string> privacies) {
    vector<int> answer;
    map<string,int> m;

    // 각 약관타입에 따라 몇달동안 유효한지 매핑
    for(string s : terms) {
        vector<string> splited = split(s, ' ');
        m.insert({splited[0], stoi(splited[1])});
    }

    // 각 개인정보 보관이 가능한지 확인
    for(int i=0; i<privacies.size(); i++) {
        vector<string> splited = split(privacies[i], ' ');
        string startDate = splited[0];
        string type = splited[1];

        string endDate = getEndDate(startDate, m[type]);

        // 만료되었다면 삭제리스트에 추가
        if (expired(today, endDate)) {
            answer.push_back(i+1);
        }
    }

    return answer;
}

후기

compare를 활용하는 방법이 익숙해지고 있어서 만족스럽다.

applyStoi 함수를 초기에 선언하지 않았는데 단순한 실수이다.

년도, 월, 일을 모두 일(date)로 통합해서 계산하는 방법도 생각해봤는데 구현된 코드를 보니 깔끔하고 바람직한 방법이지 않았나 생각이 들었다.

굳이 split등을 구현해서 함수를 여러번 호출하게 만들었어야 했나 하는 생각이 들었다.

  • 다른사람의 풀이를 확인해보니 stringstream을 활용해 ss >> date >> type 등으로 활용하는걸 봤다.
profile
amazing idiot

0개의 댓글