알고리즘, 코딩테스트/알고리즘 풀이

[프로그래머스/ 코딩테스트 완전탐색] 모의고사

jiyoon0000 2025. 2. 26. 23:15

Q. 모의고사

A.

import java.util.ArrayList;

class Solution {
    public int[] solution(int[] answers) {

	//수포자가 찍는 패턴을 배열로 저장
        int[] arr1 = {1,2,3,4,5};
        int[] arr2 = {2,1,2,3,2,4,2,5};
        int[] arr3 = {3,3,1,1,2,2,4,4,5,5};
        
        //각 수포자가 맞춘 문제 수를 저장할 변수를 초기화
        int score1 = 0;
        int score2 = 0;
        int score3 = 0;
        
        //모든 문제의 정답에 대해 수포자의 답과 비교하면서 맞을 경우 +1
        for(int i = 0; i < answers.length; i++){
            
            if(answers[i] == arr1[i % arr1.length]){
                score1++;
            }
            
            if(answers[i] == arr2[i % arr2.length]){
                score2++;
            }
            
            if(answers[i] == arr3[i % arr3.length]){
                score3++;
            }
        }
        
        //세 사람의 점수 중 최고 점수를 구하기
        int maxScore = Math.max(score1, Math.max(score2, score3));
        
        //최고 점수를 받은 수포자의 수를 센 후에 결과 배열의 크기를 결정
        //ArrayList 가변 배열을 사용
        //수포자 번호를 1,2,3으로 놓고 최고 점수를 받은 사람의 번호를 배열에 저장
        ArrayList<Integer> list = new ArrayList<>();
        if(score1 == maxScore){
            list.add(1);
        }
        
        if(score2 == maxScore){
            list.add(2);
        }
        
        if(score3 == maxScore){
            list.add(3);
        }
        
        //ArrayList에 담긴 값을 배열로 변환
        //최종 결과는 int[] answers 배열로 반환해야하므로, list의 크기만큼 배열을 만들고, 값을 넣어줌
        int[] answer = new int[list.size()];
        for(int i = 0; i < list.size(); i++){
            answer[i] = list.get(i);
        }
        
        return answer;
    }
}