(Java)프로그래머스 - 모의고사

윤준혁·2024년 2월 29일

나의 풀이

import java.util.*;

class Solution {
    public ArrayList<Integer> solution(int[] answers) {
        ArrayList<Integer> answer = new ArrayList<>();
        int[] proc1 = {1,2,3,4,5}; // 1
        int[] proc2 = {2,1,2,3,2,4,2,5};
        int[] proc3 = {3,3,1,1,2,2,4,4,5,5};
        int procPoint1 = 0; // 2
        int procPoint2 = 0;
        int procPoint3 = 0;
        
        for (int i = 0; i < answers.length; i++) { // 3
            if (answers[i] == proc1[i % 5]) procPoint1++;
            if (answers[i] == proc2[i % 8]) procPoint2++;
            if (answers[i] == proc3[i % 10]) procPoint3++;
        }
        
        int max = Math.max(procPoint1, Math.max(procPoint2, procPoint3)); // 4
        
        if (max == procPoint1) answer.add(1); // 5
        if (max == procPoint2) answer.add(2);
        if (max == procPoint3) answer.add(3);
        
        return answer;
    }
}

과정

  1. 수포자 1, 2, 3의 정답 순서가 담긴 배열을 선언
  2. 각 정답 순서에 점수를 선언
  3. 정답이 담긴 배열 answers에 정답 순서가 담긴 배열을 비교해서 각 점수를 증가
  4. procPoint1, procPoint2, procPoint3 중에 최댓값을 max로 선언
  5. 최댓값과 procPoint1, procPoint2, procPoint3를 비교하여 정답 배열 answer에 담아준다

다른 사람 풀이

import java.util.ArrayList;
class Solution {
    public int[] solution(int[] answer) {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = {2, 1, 2, 3, 2, 4, 2, 5};
        int[] c = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
        int[] score = new int[3];
        for(int i=0; i<answer.length; i++) {
            if(answer[i] == a[i%a.length]) {score[0]++;}
            if(answer[i] == b[i%b.length]) {score[1]++;}
            if(answer[i] == c[i%c.length]) {score[2]++;}
        }
        int maxScore = Math.max(score[0], Math.max(score[1], score[2]));
        ArrayList<Integer> list = new ArrayList<>();
        if(maxScore == score[0]) {list.add(1);}
        if(maxScore == score[1]) {list.add(2);}
        if(maxScore == score[2]) {list.add(3);}
        return list.stream().mapToInt(i->i.intValue()).toArray();
    }
}
  • 유지보수에 유리하도록 작성을 한듯하다 아직 부족한 점이 많이느껴지는구만

0개의 댓글