본문 바로가기

코딩 테스트

[프로그래머스] (Lv.1) 모의고사 ***

728x90

문제


수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 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하는 값을 오름차순 정렬해주세요.

 

-  출력 예시  -

정답 코드


<  내 정답 코드  >       ★    오답   

class Solution {
    public int[] solution(int[] answers) {
        int firstAnswer = 0;
        int secondAnswer = 0;
        int thirdAnswer = 0;

        // 각 찍는 패턴 배열
        int[] firstPattern = {1, 2, 3, 4, 5};
        int[] secondPattern = {2, 1, 2, 3, 2, 4, 2, 5};
        int[] thirdPattern = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};

        // 각각의 답안지 배열
        int[] firstMan = new int[answers.length];
        int[] secondMan = new int[answers.length];
        int[] thirdMan = new int[answers.length];

        // 각각의 답안지에 문제 찍기
        for (int i = 0; i < answers.length; i++) {
            firstMan[i] = firstPattern[i % 5];
            secondMan[i] = secondPattern[i % 8];
            thirdMan[i] = thirdPattern[i % 10];
        }

        // 각각의 답안지와 실제 답안지 비교하고 채점
        for (int i = 0; i < answers.length; i++) {
            if (answers[i] == firstMan[i]) {
                firstAnswer++;
            }
            if (answers[i] == secondMan[i]) {
                secondAnswer++;
            }
            if (answers[i] == thirdMan[i]) {
                thirdAnswer++;
            }
        }

        int[] tmp = {firstAnswer, secondAnswer, thirdAnswer};
        int max = tmp[0];
        int result_cnt = 0;

        for (int i = 1; i < 3; i++) {
            if (max < tmp[i]) {
                max = tmp[i];
            }
        }

        for (int i = 0; i < 3; i++) {
            if (max == tmp[i]) {
                result_cnt++;
            }
        }

        int[] answer = new int[result_cnt];

        for (int i = 0; i < 3; i++) {
            if (max == tmp[i]) {
                answer[i] = i + 1;
            }
        }

        return answer;
    }
}

 

<  내 정답 코드  >

class Solution {
    public int[] solution(int[] answers) {
        int[] scores = new int[3];
        int[] first = {1, 2, 3, 4, 5};
        int[] second = {2, 1, 2, 3, 2, 4, 2, 5};
        int[] third = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
        
        for (int i = 0; i < answers.length; i++) {
            if (answers[i] == first[i % first.length]) {
                scores[0]++;
            }
            if (answers[i] == second[i % second.length]) {
                scores[1]++;
            }
            if (answers[i] == third[i % third.length]) {
                scores[2]++;
            }
        }
        
        int max = Math.max(scores[0], Math.max(scores[1], scores[2]));
        
        List<Integer> list = new ArrayList<>();
        
        for (int i = 0; i < scores.length; i++) {
            if (max == scores[i]) {
                list.add(i + 1);
            }
        }
        
        int[] answer = new int[list.size()];
        int cnt = 0;
        
        for (Integer num : list) {
            answer[cnt++] = num;
        }
        
        return answer;
    }
}

 

< 리팩터링 이후 코드 >

class Solution {
    private static final int[] A_PATTERN = {1, 2, 3, 4, 5};
    private static final int[] B_PATTERN = {2, 1, 2, 3, 2, 4, 2, 5};
    private static final int[] C_PATTERN = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
    
    public int[] solution(int[] answers) {
    	int[][] PatternsArray = {A_PATTERN, B_PATTERN, C_PATTERN};
        int[] scoresArray = gradeExaminationPapers(PatternsArray, answers);
        return rankStudent(scoresArray);
    }

    private static int[] rankStudent(int[] scoresArray) {
        int maxScore = getMaxScore(scoresArray);
        return listToArray(sortStudent(scoresArray, maxScore));
    }

    private static List<Integer> sortStudent(int[] scoresArray, int maxScore) {
        List<Integer> studentList = new ArrayList<>();
        for (int i = 0; i < scoresArray.length; i++) {
            if (maxScore == scoresArray[i]) {
                studentList.add(i + 1);
            }
        }
        return studentList;
    }

    private static int[] listToArray(List<Integer> studentList) {
        int[] tmpArray = new int[studentList.size()];
        for (int i = 0; i < tmpArray.length; i++) {
            tmpArray[i] = studentList.get(i);
        }
        return tmpArray;
    }

    private static int scoringAnswers(int[] pattern, int[] answers) {
        int score = 0;
        for (int i = 0; i < answers.length; i++) {
            if (compareAnswer(pattern, answers, i)) {
                score++;
            }
        }
        return score;
    }

    private static boolean compareAnswer(int[] pattern, int[] answers, int idx) {
        if (answers[idx] == pattern[idx % pattern.length]) {
            return true;
        }
        return false;
    }

    private static int[] gradeExaminationPapers(int[][] PatternsArray, int[] answers) {
        int[] tmpArray = new int[PatternsArray.length];
        for (int i = 0; i < PatternsArray.length; i++) {
            tmpArray[i] = scoringAnswers(PatternsArray[i], answers);
        }
        return tmpArray;
    }

    private static int getMaxScore(int[] scoresArray) {
        return Math.max(scoresArray[0], Math.max(scoresArray[1], scoresArray[2]));
    }
}

 

<  타인 답변 코드  >

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

이것을 주의하자!


-  이 문제는 참 어려웠다. 머리를 싸매서 구현한 첫번째 코드는 일부 통과, 일부 실패로 오답이 됐다. 처음 접근 방식은 수포자 1,  2,  3 의 정답 패턴 배열을 실제 답안 배열의 크기만큼 늘린 후 실제 제출하는 답안지처럼 만드는 것이었다. 그리고 답안지와 일일이 하나씩 비교하며 정답 개수를 구했다. 그후 크기가 3인 배열에 가장 높은 맞힌 개수와 동일한 인덱스 + 1을 넣었다. 테스트에선 통과했지만, 결국 통과하지 못했다... ㅠㅠ

 

-  하지만 좋은 인사이트를 얻었다. 어떤 배열의 원소를 계속 반복하고 싶을 때,  (  i  %  arr.length  )하면 가능하다. 그러면 해당 크기의 인덱스를 0부터 마지막 원소까지 계속 반복하게 된다. 이 원리가 문제 해결에 필요하다.

 

-  정답 코드에선 scores 배열을 만든 후, for 문을 돌려 정답지의 원소와 수포자의 배열 원소들끼리 하나씩 비교한다. 이때 각각의 수포자 배열 탐색에서 (  i  %  arr.length  ) 을 사용한다. 그리고 if 문으로 동일하면 scores 배열의 각 자리에 + 1 씩 한다.

 

-  scores [ ] 배열에 각 맞은 정답 개수가 기록되었다면, 이제 가장 높은 수를 구해야 한다. max 를 구한 뒤 해당 max 와 동일한 정답 개수를 가진 원소들만 새로운 ArrayList 에 넣는다. 리스트를 사용한 이유는 총 원소의 개수를 모르기 때문에 길이에 유연한 리스트를 선택했다. 하지만 나중에 다시 배열로 바꿔야 하는 번거로움이 있다. 그래서 아예 배열로 만드는 방법도 있다.

 

-  타인 답변 코드를 보면, 전체적인 로직은 비슷하다. 그러나 실제 정답지와 수포자들의 정답지를 비교할 때 2차원 배열을 사용했다는 점이 다르다. 이런 부분은 알고 있으면 좋겠다.