GitHubSeob

C++ / 프로그래머스 / 위클리 챌린지 4주차 / 직업군 추천하기 본문

Programmers/Level 1

C++ / 프로그래머스 / 위클리 챌린지 4주차 / 직업군 추천하기

GitHubSeob 2021. 8. 26.

문제

https://programmers.co.kr/learn/courses/30/lessons/84325

 

코딩테스트 연습 - 4주차

개발자가 사용하는 언어와 언어 선호도를 입력하면 그에 맞는 직업군을 추천해주는 알고리즘을 개발하려고 합니다. 아래 표는 5개 직업군 별로 많이 사용하는 5개 언어에 직업군 언어 점수를 부

programmers.co.kr

문제풀이

문제 자체는 어렵지 않은데 띄어쓰기 기준 string 자르기, 사전 순 정렬이 조금 귀찮았다.

 vector<string>name = { "SI", "CONTENTS", "HARDWARE", "PORTAL", "GAME" };

table의 직업군이 이 순으로 나오기 때문에 따로 name이라는 벡터를 만들었다.

점수가 같을 경우 사전 순으로 정렬해야 되기 때문에 편의성을 위해서 만든 벡터.

for (idx = 0; idx < 5; ++idx) {
        stringstream ss(table[idx]);
        int cnt = 0;
        while (ss >> buffer) {
            for (idx2 = 0; idx2 < languages.size(); ++idx2) {
                if (buffer == languages[idx2]) {
                    score[idx] += (preference[idx2] * (6 - cnt));
                }
            }
            cnt++;
        }
    }

띄어쓰기 기준 자르기 위해 stringstream을 썼다.

table의 행과 점수의 합이 6이므로 6-cnt값과 해당 언어 선호도 값을 곱해 score벡터에 저장해준다.

idx는 직업군 항목이 5개이므로 5까지, table에는 직업군 항목 하나, 점수 5개가 있으므로 총 cnt는 0~5의 값을 이용한다.

 

int max_score = 0;
    int max_idx = 0;
    for (idx = 0; idx < 5; ++idx) {
        if (score[idx] > max_score) {
            max_score = score[idx];
            max_idx = idx;
        }
        else if (score[idx] == max_score)
            if (name[idx].compare(name[max_idx]) < 0)
                max_idx = idx;
    }

    return name[max_idx];

max_score은 최대 점수, max_idx는 최대 점수일 때의 idx이고, 점수가 같은 항목이 있을 때 사전 순으로 비교하여 더 빠른 항목의 정보 값을 max_idx에 저장한다.

모두 비교했으면 해당 항목을 return 한다.

 

 

코드

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

using namespace std;

string solution(vector<string> table, vector<string> languages, vector<int> preference) {
    vector<int>score(5, 0);
    vector<vector<string>>score_table(5, vector<string>(0, ""));
    vector<string>name = { "SI", "CONTENTS", "HARDWARE", "PORTAL", "GAME" };

    int idx = 0;
    int idx2 = 0;
    int cnt = 0;
    string buffer = "";

    for (idx = 0; idx < 5; ++idx) {
        stringstream ss(table[idx]);
        int cnt = 0;
        while (ss >> buffer) {
            for (idx2 = 0; idx2 < languages.size(); ++idx2) {
                if (buffer == languages[idx2]) {
                    score[idx] += (preference[idx2] * (6 - cnt));
                }
            }
            cnt++;
        }
    }
    int max_score = 0;
    int max_idx = 0;
    for (idx = 0; idx < 5; ++idx) {
        if (score[idx] > max_score) {
            max_score = score[idx];
            max_idx = idx;
        }
        else if (score[idx] == max_score)
            if (name[idx].compare(name[max_idx]) < 0)
                max_idx = idx;
    }

    return name[max_idx];
}