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

smi·2023년 2월 6일
0

📚 문제 정의

완전 탐색 문제

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

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

📝 제한 사항

  • 시험은 최대 10,000 문제로 구성되어있습니다.
  • 문제의 정답은 1, 2, 3, 4, 5중 하나입니다.
  • 가장 높은 점수를 받은 사람이 여럿일 경우, return하는 값을 오름차순 정렬해주세요.

📝 입출력 예

answersresult
[1,2,3,4,5][1]
[1,3,2,4,2][1,2,3]

💡 코드

import java.util.*;

class Solution {
    public int[] solution(int[] answers) {
        int[] one = { 1, 2, 3, 4, 5 };
        int[] two = { 2, 1, 2, 3, 2, 4, 2, 5 };
        int[] three = { 3, 3, 1, 1, 2, 2, 4, 4, 5, 5 };
        int oneScore = 0; int twoScore = 0; int threeScore = 0;
        Queue<Integer> q = new LinkedList<>();
        
        for(int i = 0; i < answers.length; i++) {
            if(answers[i] == one[i % 5]) oneScore++;
            if(answers[i] == two[i % 8]) twoScore++;
            if(answers[i] == three[i % 10]) threeScore++;
        }
        
        int maxScore = Math.max(Math.max(oneScore, twoScore), threeScore);
        if(maxScore == oneScore) q.add(1);
        if(maxScore == twoScore) q.add(2);
        if(maxScore == threeScore) q.add(3);
        
        return q.stream().mapToInt(Integer::intValue).toArray();
    }
}

💡 다른 분의 코드

import java.util.*;

class Solution {
    public static int[] solution(int[] answers) {
        int[][] patterns = {
                {1, 2, 3, 4, 5},
                {2, 1, 2, 3, 2, 4, 2, 5},
                {3, 3, 1, 1, 2, 2, 4, 4, 5, 5}
        };

        int[] hit = new int[3];
        for(int i = 0; i < hit.length; i++) {
            for(int j = 0; j < answers.length; j++) {
                if(patterns[i][j % patterns[i].length] == answers[j]) hit[i]++;
            }
        }

        int max = Math.max(hit[0], Math.max(hit[1], hit[2]));
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < hit.length; i++)
            if(max == hit[i]) list.add(i + 1);

        int[] answer = new int[list.size()];
        int cnt = 0;
        for(int num : list)
            answer[cnt++] = num;
        return answer;
    }
}

profile
공부한 거 올려요 :)

0개의 댓글