Coding Test - cpp/String
[프로그래머스 lv 1 ] - 4주차 직업군 추천
에드윈H
2021. 10. 1. 00:26
https://programmers.co.kr/learn/courses/30/lessons/84325
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
string solution( vector<string> table, vector<string> languages, vector<int> preference ) {
map<string, int> m;
int size1 = languages.size();
//각 언어와 선호도 점수 m
for( int i = 0; i < size1; i++ )
{
m[languages[i]] = preference[i];
}
vector<int> results;
int tableSize = table.size();
//각 직업군의 선호도 반영 점수 계산
for( int i = 0; i < tableSize; i++ )
{
//table 각 직업군의 언어별 점수 확인
string value = table[i];
int index = 0;
map<string, int> jobValue;
string target;
int curScore = 6;
while( value[index] != '\0' )
{
if( value[index] == ' ' )
{
jobValue[target] = curScore--;
target = "";
index++;
}
target += value[index++];
}
jobValue[target] = curScore;
int score = 0;
for( int j = 0; j < size1; j++ )
{
score += m[languages[j]] * jobValue[languages[j]];
}
results.push_back( score );
}
int max = -214000000;
int i;
int maxIndex = 0;
//제일 높은 점수 확인
for( i = 0; i < results.size(); i++ )
{
if( max < results[i] )
{
max = results[i];
maxIndex = i;
}
}
map<int, string> m3;
vector<string> resultString;
m3[0] = "SI"; m3[1] = "CONTENTS"; m3[2] = "HARDWARE"; m3[3] = "PORTAL"; m3[4] = "GAME";
for( int i = 0; i < results.size(); i++ )
{
if( results[i] == max )
{
resultString.push_back( m3[i] );
}
}
if( 2 <= resultString.size() )
{
sort( resultString.begin(), resultString.end(), less<>() );
}
return resultString[0];
}
정리- 함수추출,for문 불필요제거
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
void CalcScore( string value, map<string, int>& jobValue )
{
string target;
int curScore = 6;
int index = 0;
//
while( value[index] != '\0' )
{
if( value[index] == ' ' )
{
jobValue[target] = curScore--;
target = "";
index++;
}
target += value[index++];
}
jobValue[target] = curScore;
}
string solution( vector<string> table, vector<string> languages, vector<int> preference ) {
map<string, int> m;
int size1 = languages.size();
//각 언어와 선호도 점수 m
for( int i = 0; i < size1; i++ )
{
m[languages[i]] = preference[i];
}
vector<int> results;
int tableSize = table.size();
int max = -214000000;
for( int i = 0; i < tableSize; i++ )
{
//table 각 직업군의 언어별 선호도 점수 확인
string value = table[i];
map<string, int> jobValue;
CalcScore( value, jobValue );
int score = 0;
for( int j = 0; j < size1; j++ )
{
score += m[languages[j]] * jobValue[languages[j]];
}
results.push_back( score );
if( max < score )
{
max = score;
}
}
map<int, string> m3;
vector<string> resultString;
m3[0] = "SI"; m3[1] = "CONTENTS"; m3[2] = "HARDWARE"; m3[3] = "PORTAL"; m3[4] = "GAME";
//제일 큰값이 몇개인지 확인하기 위해
for( int i = 0; i < results.size(); i++ )
{
if( results[i] == max )
{
resultString.push_back( m3[i] );
}
}
//제일높은 점수가 1개 초과한다면 사전순 정렬로 제일 앞인거
if( 1 < resultString.size() )
{
sort( resultString.begin(), resultString.end(), less<>() );
}
return resultString[0];
}