본문 바로가기
이전

프로그래머스 : 모의고사 [C++]

by 이포터 2022. 11. 4.

문제 링크

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

 

문제 설명

1번 수포자가 찍는 방식: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
2번 수포자가 찍는 방식: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, ...
3번 수포자가 찍는 방식: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, ...

1. 1번 문제부터 마지막 문제까지의 정답이 순서대로 들은 배열 answers가 주어졌을 때
2. 가장 많은 문제를 맞힌 사람이 누구인지 배열에 담아 return 하도록 solution 함수를 작성해주세요.

 

문제 입출력 예)

answers result
[1,2,3,4,5] [1]
[1,3,2,4,2] [1,2,3]

 

문제 풀이 1/2

person1의 정답, person2의 정답, person3의 정답을 각각 배열에 넣어주었다.

문제의 길이만큼 반복문을 돌려서 정답이 맞는지 처리를 해주고, sort를 통해 값을 정렬해 주었다.

이렇게되면, person의 첫번째 값은 가장 많이 맞춘 인원이 될 것이고, 그 이후 person의 첫번째값과 같은 값을 push_back을 해줬다.

#include <string>
#include <vector>
#include <iostream>
#include <utility>
#include <algorithm>

using namespace std;

bool compare(const pair<int, int> &a, const pair<int, int> &b)
{
    if (a.first == b.first)
    {
        return a.second < b.second;
    }
    return a.first > b.first;
}

vector<int> solution(vector<int> answers) {
    vector<int> answer;
    vector<pair<int,int>> person;
    vector<int> person1 = {1,2,3,4,5};
    vector<int> person2 = {2,1,2,3,2,4,2,5};
    vector<int> person3 = {3,3,1,1,2,2,4,4,5,5};
    for(int i=0; i<3; i++)
        person.push_back(make_pair(0, i+1));
    
    for(int i=0; i<answers.size(); i++){
        if(person1[i%5] == answers[i]) person[0].first++;
        if(person2[i%8] == answers[i]) person[1].first++;
        if(person3[i%10] == answers[i]) person[2].first++;
    }
    
    sort(person.begin(), person.end(), compare);
    answer.push_back(person[0].second);
    for(int i=1; i<3; i++){
        if(person[i].first == person[0].first)
            answer.push_back(person[i].second);
    }
    
    
    return answer;
}

 

문제 풀이 2/2

다른 문제풀이를 찾아본 결과

max_element(), min_element()가 있다는 사실을 알게 되었다.

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

using namespace std;

vector<int> one = {1,2,3,4,5};
vector<int> two = {2,1,2,3,2,4,2,5};
vector<int> thr = {3,3,1,1,2,2,4,4,5,5};

vector<int> solution(vector<int> answers) {
    vector<int> answer;
    vector<int> they(3);
    for(int i=0; i<answers.size(); i++) {
        if(answers[i] == one[i%one.size()]) they[0]++;
        if(answers[i] == two[i%two.size()]) they[1]++;
        if(answers[i] == thr[i%thr.size()]) they[2]++;
    }
    int they_max = *max_element(they.begin(),they.end());
    for(int i = 0; i< 3; i++) {
        if(they[i] == they_max) answer.push_back(i+1);
    }
    return answer;
}

 

리뷰

max_element를 사용했다.

1. max_element로 최대값을 뽑아내고

2. 그 최대값과 같은 변수값을 결과에 push_back 시켰다.

 

sort를 따로 안해도되고, 문제풀이가 더욱 간단해졌다.

댓글