프로그래머스 lv1 모의고사

이성준·2022년 6월 18일
0

알고리즘

목록 보기
9/13

사이트 : 프로그래머스

푼 날짜 : 2022-06-18
난이도 : LV1
제목 : 모의고사

코드

import java.util.ArrayList;
import java.util.Arrays;

public class 모의고사 {
    
    public ArrayList<Integer> solution(int[] answers) {

        int [] math1 = new int[]{1, 2, 3, 4, 5};
        int [] math2 = new int[]{2,1,2,3,2,4,2,5};
        int [] math3 = new int[]{3,3,1,1,2,2,4,4,5,5};
        int[][] math = new int[3][answers.length];
        int temp =0 ;
        int[] result = {0,0,0};


        for (int i = 0; i < answers.length; i++) {
            if(answers[i]==math1[i%5]){
                result[0]++;
            }
            if(answers[i]==math2[i%8]){
                result[1]++;
            }
            if(answers[i]==math3[i%10]){
                result[2]++;
            }

        }

        temp = Math.max(temp,result[0]);
        temp =  Math.max(temp,result[1]);
        temp =  Math.max(temp,result[2]);

        ArrayList<Integer> answer = new ArrayList<>();

        for (int i = 0; i < 3; i++) {
            if(result[i]>=temp){
                answer.add(i+1);
            }
        }

        System.out.println(answer);
        return answer;
    }

풀이

  1. 일단 각각 수포자 찍는방식이 일정한 패턴으로 반복되고 있으므로 반복되는 부분을 배열로 만들어준다. 맞은 답 갯수를 저장할 result 배열을 선언한다.
  2. 정답배열의 크기만큼 for문을 돌면서 answer 배열과 math 배열(나머지연산으로 같은배열을 계속 반복)의 원소를 비교하며 각각 수포자가 맞은 답 갯수를 구한다
  3. 정답갯수의 최댓값을 구하고 정답갯수랑 정답갯수의 최댓값을 비교하여 정답갯수의 최댓값보다 같거나 크면 인덱스를 넣는다.

0개의 댓글