본문 바로가기

ALGORITHM/OTHER

[c++] 모의고사 (완전탐색)

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

 

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

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

programmers.co.kr

 

완전탐색 그냥 구현 문제같다.

 

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> answers) {
    vector<int> answer;
    
    int count = (int)answers.size();
    int mathAnswer1[5] = {1, 2, 3, 4, 5};
    int mathAnswer2[8] = {2, 1, 2, 3, 2, 4, 2, 5};
    int mathAnswer3[10] = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
    int solve[4] = {0, 0, 0, 0};
    int k;
    
    
    for (int i=1; i<=3; i++) {
        for (int j=0; j<count; j++) {
            if (i==1) {
                k = j % 5;
                if (answers[j] == mathAnswer1[k]) {
                    solve[i]++;
                }
            }
            
            if (i==2) {
                k = j % 8;
                if (answers[j] == mathAnswer2[k]) {
                    solve[i]++;
                }
            }
            
            if (i==3) {
                k = j % 10;
                if (answers[j] == mathAnswer3[k]) {
                    solve[i]++;
                }
            }
        }
    }
    
    int maxValue = 0;
    
    for (int i=1; i<=3; i++) {
        if (maxValue < solve[i]) {
            maxValue = solve[i];
        }
    }
    
    for (int i=1; i<=3; i++) {
        if (maxValue == solve[i]) {
            answer.push_back(i);
        }
    }
    
    return answer;
}

 

코드를 이쁘게 바꿔보자

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> answers) {
    vector<int> answer;
    
    int count = (int)answers.size();
    int mathAnswer1[5] = {1, 2, 3, 4, 5};
    int mathAnswer2[8] = {2, 1, 2, 3, 2, 4, 2, 5};
    int mathAnswer3[10] = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
    int solve[4] = {0, 0, 0, 0};

    for (int i=0; i<count; i++) {
        if (answers[i] == mathAnswer1[i%5]) {
            solve[1]++;
        }
        if (answers[i] == mathAnswer2[i%8]) {
            solve[2]++;
        }
        if (answers[i] == mathAnswer3[i%10]) {
            solve[3]++;
        }
    }
    
    int maxValue = *max_element(solve, solve + 4);
    
    for (int i=1; i<=3; i++) {
        if (maxValue == solve[i]) {
            answer.push_back(i);
        }
    }
    
    return answer;
}

 

배운 것: max_element 

vector를 사용한다면 begin과 end를 넣어주면 된다.

'ALGORITHM > OTHER' 카테고리의 다른 글

[c++] 실패율 (프로그래머스 - 구현)  (0) 2021.06.22
[c++] 신규 아이디 추천 (프로그래머스-구현)  (0) 2021.06.21
[c++] K번째수  (0) 2021.05.12
[c++] 완주하지 못한 선수  (0) 2021.05.11
[c++] 폰켓몬 (set, map)  (0) 2021.05.10