본문 바로가기

algorithm/프로그래머스

프로그래머스_모의고사(C++, JAVA)

 

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

 

프로그래머스

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

programmers.co.kr

[문제 풀이]

단순 탐색을 이용하여 문제를 풀었습니다.

 

세 사람의 패턴을 세 개의 배열에 저장해둔 후 반복을 통하여 문제를 풀었습니다.

[C++]

#include <string>
#include <vector>

using namespace std;

int p1[5] = { 1,2,3,4,5 };
int p2[8] = { 2,1,2,3,2,4,2,5 };
int p3[10] = { 3,3,1,1,2,2,4,4,5,5 };


vector<int> solution(vector<int> answers) {

    vector<int> result;

    int a = 0, b = 0, c = 0, max = 0;

    for (int i = 0; i < answers.size(); i++) {

        if (answers[i] == p1[i % 5])
            a++;

        if (answers[i] == p2[i % 8])
            b++;

        if (answers[i] == p3[i % 10])
            c++;

        if (i == answers.size() - 1) {
            
            if (a >= b)
                max = a;
            else
                max = b;

            if (max <= c)
                max = c;

            if (a == max)
                result.push_back(1);
            if (b == max)
                result.push_back(2);
            if (c == max)
                result.push_back(3);
        }
    }

    return result;

}

[JAVA]

import java.util.*;

class Solution {
    public int[] solution(int[] answers) {
        int max = 0;
        int[] score = new int[3];
        
        int[][] player = {
              {1, 2, 3, 4, 5}
            , {2, 1, 2, 3, 2, 4, 2, 5}
            , {3, 3, 1, 1, 2, 2, 4, 4, 5, 5}
        };
        
        for(int k = 0; k < 3; k++){
            for(int i = 0; i < 3; i++){
                int count = 0;
                int j = 0;
                for(int idx = 0; idx < answers.length; idx++){
                    
                    if(answers[idx] == player[i][j])
                        count++;
                    
                    j++;
                    
                    if(j == player[i].length)
                        j = 0;
                }
                score[i] = count;
                if(max < count)
                    max = count;
            }
            
        }
        
        ArrayList<Integer> winner = new ArrayList<>();
        for(int i = 0; i < score.length; i++){
            if(max == score[i])
                winner.add(i + 1);
        }
        Collections.sort(winner);
        
        return winner.stream().mapToInt(Integer::intValue).toArray();
    }
}