프로그래머스 모의고사 자바

2023. 5. 7. 17:09코딩테스트/프로그래머스

https://school.programmers.co.kr/learn/courses/30/lessons/42840

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

이 문제에서는 입력값이 answers 라는 배열만 있다. 

1, 2 ,3번 수포자는 문제에서 규칙을 알려주고 최대 문제 개수를 제시하였으므로 이를 통해 1, 2, 3 번의 답을 최대 10000개가 되도록 입력을 한 후 answer와 비교하는 방식으로 문제를 해결하면 될 것이다.

 

따라서 고려해야 할 점은

 

1. 문제에서 글로 제시된 것을 통해 수포자 1, 2, 3이 최대 10000개 일 경우의 답을 배열로 만든 후

2. 정답과 비교하여 수포자들의 맞은 개수를 구한 후

3. 정답의 개수가 최대인 수포자를 배열로 구해주면 된다.

 

이 문제로 배열로 풀이를 하면 다음과 같다.

import java.util.Arrays;

public class Solution42840 {

    int[] array1 = new int[10000];
    int[] array2 = new int[10000];
    int[] array3 = new int[10000];

    int[] rule1 = {1, 2, 3, 4, 5};
    int[] rule2 = {2, 1, 2, 3, 2, 4, 2, 5};
    int[] rule3 = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};

    // 규칙에 맞게 배열에 값 넣어주는 메소드
    public void insert(int[] array, int[] rule) {
        int index = 0;

        for (int i = 0; i < array.length; i++) {
            array[i] = rule[index];

            index++;

            if (index == rule.length) {
                index = 0;
            }
        }
    }

    // 최대로 맞은 사람 확인
    public int[] check(int[] answers) {
        insert(array1, rule1);
        insert(array2, rule2);
        insert(array3, rule3);

        int[] correct = new int[3];

        // 각 사람의 맞은 개수 구하기
        for (int i = 0; i < answers.length; i++) {

            if (answers[i] == array1[i]) {
                correct[0]++;
            }

            if (answers[i] == array2[i]) {
                correct[1]++;
            }

            if (answers[i] == array3[i]) {
                correct[2]++;
            }
        }

        int max = correct[0];

        // 최대로 맞은 문제 개수 구하기
        for (int i = 0; i < correct.length; i++) {

            if (max < correct[i]) {
                max = correct[i];
            }
        }

        int index = 0;
        int[] temp = new int[3];

        for (int i = 0; i < correct.length; i++) {

            if (max == correct[i]) {
                temp[index] = i + 1;
                index++;
            }
        }

        int[] result = new int[index];

        for (int i = 0; i < index; i++) {
            result[i] = temp[i];
        }

        return result;
    }

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

        int[] result = check(answers);

        return result;
    }

    public static void main(String[] args) {
        Solution42840 s = new Solution42840();
        int[] answers = {1,3,2,4,2};

        int[] result = s.solution(answers);

        System.out.println(Arrays.toString(result));
    }
}