Algorithm/Programmers

[Programmers - c++] 모의고사

tjddneva 2022. 2. 7. 23:05

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

 

코딩테스트 연습 - 모의고사

수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 1번 문제부터 마지막 문제까지 다음과 같이 찍습니다. 1번 수포자가 찍는

programmers.co.kr

 

배열에 미리 패턴을 받아놓고 answers vector 를 탐색하면서 맞나 틀리나 확인후 맞으면 변수 값을 증가 시키면 끝나는 문제였다. 가장 높은 점수를 받은 사람이 여럿일 경우를 처리하는데 좀 시간이 걸렸는데 뭔가 굉장히 비효율적으로 한 것 같다. 코드를 보면 

 

우선

int a[5] = {1,2,3,4,5};
int b[8] = {2,1,2,3,2,4,2,5};
int c[10] = {3,3,1,1,2,2,4,4,5,5};

전역에 수포자들의 패턴을 담아 놓는다. 

 

그리고

    int ii = 0;
    for(int i=0; i<answers.size(); i++){
        if(a[ii] == answers[i]) supo1++;
        ii++;
        if(ii>4) ii = 0;
    }

이런 식으로 수포자의 패턴과 answers vector 를 동시에 보면서 맞은 개수를 supo1 배열에 저장한다. 수포자2와 수포자3도 마찬가지로 한다. 

 

마지막으로

    int win = max({supo1,supo2,supo3});
    if(win == supo1){
        answer.push_back(1);
        if(supo1==supo2) answer.push_back(2);
        if(supo1==supo3) answer.push_back(3);
    }
    else if(win == supo2){
        answer.push_back(2);
        if(supo2==supo3) answer.push_back(3);
    }
    else{
        answer.push_back(3);
    }

max 함수를 이용해서 제일 많이 맞춘 수포자를 찾고 가장 높은 점수를 받은 수포자가 여럿인 경우에 대해 처리를 해주었다. 이런 방식보다 훨씬 효율적인 방식이 있을 텐데 뭔가 복잡하게 하게 되었다ㅠ

 

아래는 전체 코드이다.

#include <iostream>
#include <cstring>
#include <string.h>
#include <string>
#include <cmath>
#include <vector>
#include <math.h>
#include <algorithm>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <tuple>
#include <utility>
#include <typeinfo>
#include <iomanip>
#include <set>
#include <map>

using namespace std;

int a[5] = {1,2,3,4,5};
int b[8] = {2,1,2,3,2,4,2,5};
int c[10] = {3,3,1,1,2,2,4,4,5,5};
vector<int> solution(vector<int> answers) {
    vector<int> answer;
    
    int supo1=0, supo2=0, supo3=0;
    
    int ii = 0;
    for(int i=0; i<answers.size(); i++){
        if(a[ii] == answers[i]) supo1++;
        ii++;
        if(ii>4) ii = 0;
    }
    
    int jj = 0;
    for(int i=0; i<answers.size(); i++){
        if(b[jj] == answers[i]) supo2++;
        jj++;
        if(jj>7) jj = 0;
    }
    
    int kk = 0;
    for(int i=0; i<answers.size(); i++){
        if(c[kk] == answers[i]) supo3++;
        kk++;
        if(kk>9) kk = 0;
    }
    
    int win = max({supo1,supo2,supo3});
    if(win == supo1){
        answer.push_back(1);
        if(supo1==supo2) answer.push_back(2);
        if(supo1==supo3) answer.push_back(3);
    }
    else if(win == supo2){
        answer.push_back(2);
        if(supo2==supo3) answer.push_back(3);
    }
    else{
        answer.push_back(3);
    }
    
    return answer;
}