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

김현진·2022년 1월 16일
0

코테준비

목록 보기
14/22
  • 문제 해결:
    주어진 답과 각 학생들이 찍은 답을 비교하여 정답 개수를 구하고 배열로 만들어 반환하는 문제이다.

    먼저 각 학생이 찍은 답은 정해진 패턴이 있었기 때문에 주어진 정답 배열에서
    각각 정답 번호를 꺼내어 각 학생이 찍은 답을 비교하였다.

    다음으로 각 학생의 정답이 많은 횟수로 학생들의 번호를 배열에 넣었고
    정답횟수가 같다면 번호의 오름차순으로 넣었다.
import java.util.*;

class Solution {
    public int[] solution(int[] answers) {
        int length = answers.length;
        int a_score = 0; //각 학생의 정답 횟수
        int b_score = 0; 
        int c_score = 0;
        
        for(int i=0;i<answers.length;i++){
            int a_ans = 0; // 각 학생이 찍은 답
            int b_ans = 0;
            int c_ans = 0;
            
            if(i%5==0){ // 1번 학생의 정답 패턴
                a_ans = 1;
            } else if(i%5==1){
                a_ans = 2;
            } else if(i%5==2){
                a_ans = 3;
            } else if(i%5==3){
                a_ans = 4;
            } else a_ans = 5;
            
            if(i%2==0){ // 2번 학생의 정답 패턴
                b_ans = 2;
            } else if(i%8==1){
                b_ans = 1;
            } else if(i%8==3){
                b_ans = 3;
            } else if(i%8==5){
                b_ans = 4;
            } else b_ans = 5;
            
            if(i%10==0 || i%10==1){ // 3번 학생의 정답 패턴
                c_ans = 3;
            }else if(i%10==2||i%10==3){
                c_ans = 1;
            }else if(i%10==4||i%10==5){
                c_ans = 2;
            }else if(i%10==6||i%10==7){
                c_ans = 4;
            }else c_ans = 5;
            
            if(a_ans == answers[i]) a_score++; //정답이라면 
            if(b_ans == answers[i]) b_score++;
            if(c_ans == answers[i]) c_score++;
        }
        
        int max_score = a_score; //최대 문제 맞춘 횟수를 기록
        
        if(max_score<b_score){
            max_score = b_score;
        }
        
        if(max_score<c_score){
            max_score = c_score;
        }
        
        ArrayList<Integer> result = new ArrayList<>();
        if(a_score==max_score) result.add(1); //문제를 가장 많이 맞춘 사람만 추가
        if(b_score==max_score) result.add(2);
        if(c_score==max_score) result.add(3);
        
        return result.stream().mapToInt(Integer::intValue).toArray();
    }
}

0개의 댓글