본문 바로가기
ps/알고리즘

99클럽 코테스터디 39일차 TIL 프로그래머스- 로또의 최고 순위와 최저 순위

by nastorond 2024. 8. 29.

로또의 최고 순위와 최저 순위

프로그래머스 Level 1 Greedy
문제 링크

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 설명

민우가 구매한 로또의 번호 정보가 손실되어 있고, 0은 손실된 값. 아닌 숫자는 민우가 구매한 숫자다.
민우가 당첨될 수 있는 최대 순위와 최소 순위를 리턴해주면 되는 문제

문제 풀이

로또번호를 하나하나 체크하며 0인 부분과 아닌 부분을 따로 카운트 해준 뒤, 하드코딩하여 리턴해줬다.

코드

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

using namespace std;

vector<int> solution(vector<int> lottos, vector<int> win_nums) {
    vector<int> answer;

    int checkNum[6], lim = lottos.size(), score=0, cnt=0;
    memset(checkNum, -1, sizeof(checkNum));

    for (int i=0; i<lim; i++) {
        if (lottos[i] == 0) {
            cnt++;
            continue;
        }
        if (find(win_nums.begin(), win_nums.end(), lottos[i]) != win_nums.end()) {
            checkNum[i] = 1;
            score++;
        } else {
            checkNum[i] = 0;
        }
    }

    if (score + cnt == 6) {
        answer.push_back(1);
    } else if (score + cnt == 5) {
        answer.push_back(2);
    } else if (score + cnt == 4) {
        answer.push_back(3);
    } else if (score + cnt == 3) {
        answer.push_back(4);
    } else if (score + cnt == 2) {
        answer.push_back(5);
    } else {
        answer.push_back(6);
    }

    switch (score) {
        case 6:
            answer.push_back(1);
            break;
        case 5:
            answer.push_back(2);
            break;
        case 4:
            answer.push_back(3);
            break;
        case 3:
            answer.push_back(4);
            break;
        case 2:
            answer.push_back(5);
            break;
        default:
            answer.push_back(6);
    }

    return answer;
}

하드코딩 되어있어 풀이가 많이 번잡해 gpt 한테 최적화 해달라고 해봤다.

최적화 코드

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

using namespace std;

vector<int> solution(vector<int> lottos, vector<int> win_nums) {
    int cnt_zeros = count(lottos.begin(), lottos.end(), 0);
    int cnt_matches = 0;

    for (int num : lottos) {
        if (find(win_nums.begin(), win_nums.end(), num) != win_nums.end()) {
            cnt_matches++;
        }
    }

    int max_rank = 7 - (cnt_matches + cnt_zeros);
    int min_rank = 7 - cnt_matches;

    if (max_rank > 6) max_rank = 6;
    if (min_rank > 6) min_rank = 6;

    return {max_rank, min_rank};
}

Python 코드

def solution(lottos, win_nums):
    cnt_zeros = lottos.count(0)
    cnt_matches = sum(1 for num in lottos if num in win_nums)

    max_rank = 7 - (cnt_matches + cnt_zeros)
    min_rank = 7 - cnt_matches

    if max_rank > 6:
        max_rank = 6
    if min_rank > 6:
        min_rank = 6

    return [max_rank, min_rank]

회고

풀이를 떠올리고 나서, 어떻게하면 최적화 해야하지 보다는 그냥 답만 맞으면 된다고 생각해서 제출했었는데,
gpt 가 풀어준 걸 보니 최적화는 필수 인 것 같다