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

bien·2024년 5월 29일
0

코딩테스트

목록 보기
8/14

문제

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


풀이

💻 결과 코드

class Solution {
    public int[] solution(int[] answers) {
        int seqOne = 0;
        int seqTwo = 0;
        int seqThree = 0;

        int scoreOne = 0;
        int scoreTwo = 0;
        int scoreThree = 0;

        int[] one = new int[]{1,2,3,4,5};
        int[] two = new int[]{2,1,2,3,2,4,2,5};
        int[] three = new int[]{3,3,1,1,2,2,4,4,5,5};

        for (int i = 0; i < answers.length; i++) {
            if (answers[i] == one[seqOne]) {
                scoreOne++;
            }

            if (answers[i] == two[seqTwo]) {
                scoreTwo++;
            }

            if (answers[i] == three[seqThree]) {
                scoreThree++;
            }
            
            seqOne++;
            seqTwo++;
            seqThree++;
            
            if (seqOne >= one.length) {seqOne = 0;}
            if (seqTwo >= two.length) {seqTwo = 0;}
            if (seqThree >= three.length) {seqThree = 0;}
        }
        
        if (scoreOne == scoreTwo && scoreTwo == scoreThree) {
            return new int[]{1,2,3};
        } else if(scoreOne == scoreTwo && scoreTwo > scoreThree) {
            return new int[]{1,2};
        } else if(scoreOne == scoreThree && scoreThree > scoreTwo) {
            return new int[]{1,3};
        } else if(scoreTwo == scoreThree && scoreTwo > scoreOne) {
            return new int[]{2,3};
        } else if(scoreOne > scoreTwo && scoreOne > scoreThree) {
            return new int[]{1};
        } else if(scoreTwo > scoreThree && scoreTwo > scoreOne) {
            return new int[]{2};
        } else if(scoreThree > scoreOne && scoreThree > scoreTwo) {
            return new int[]{3};
        } else {
            return new int[]{};
        }
    }
}

고민사항

코드를 작성하면서 고민했던 주요 사항은 아래와 같다.

  1. 반복적인 인덱스 관리
    • 각 수포자의 패턴 인덱스를 수동으로 증가시키고 범위를 벗어날 때마다 초기화하는 방식으로 관리하고 있다.
      • 코드가 복잡하고 가독성이 낮으며, 유지보수에도 불리하다.
      • 작성하면서 어디서 seq를 증가시켜야 하나 혼란스러웠다.
  2. 점수 비교의 비효율성
    • 각 수포자의 점수를 비교해 최종 결과를 반환하는 부분을 다 조건문으로 처리했다.
      • 성능적으로 단순한 조건문 비교가 빠르다고 느낀적이 있어서 그렇게 구현해봤는데, 코드의 가독성이 떨어지고 논리적으로 복잡하다.
    • 조건문이 많아질 수록 코드의 길이와 복잡성이 증가하여 버그 발생 가능성이 높아진다.

💻 코드 리팩토링

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();
    }
}

주요 개선 사항

  1. 묘듈러 연산을 통한 인덱스 관리
    • 모듈러 연산주기성을 가지는 패턴을 다룰때 매우 유용하다.
    • 반복적인 인덱스 증가와 초기화를 수동으로 처리하는 대신, 모듈러 연산(%)을 사용하여 패턴의 인덱스를 처리하면 코드가 간결해지고 명확해진다.

  1. 점수 배열을 통한 비교
    • 배열을 사용해 데이터(점수)를 저장하고, 이를 순회하는 방식은 데이터의 비교 및 처리를 효율적으로 할 수 있는 방법이다.
    • 최대값 계산의 경우, Math.max 함수를 사용해 간단하게 해결할 수 있다.
    • 동적 리스트를 사용해 수포자를 동적으로 리스트에 추가하고, 최종적으로 배열로 변환한다.
profile
Good Luck!

0개의 댓글