애플리케이션 개발/알고리즘

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

sofiaaa 2022. 6. 30. 23:36
반응형

모의고사

 

문제

1, 2, 3번째의 반복되는 답변이

해당 문제의 해답과 가장 많이 맞는 사람을 출력.

만약 문제가 동일하면 오름차순.

 

 

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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

        int[] stu1 = new int[]{1, 2, 3, 4, 5};
        int[] stu2 = new int[]{2, 1, 2, 3, 2, 4, 2, 5};
        int[] stu3 = new int[]{3, 3, 1, 1, 2, 2, 4, 4, 5, 5};

        int score1 = 0;
        int score2 = 0;
        int score3 = 0;

        int[] answer1 = new int[answers.length];
        int[] answer2 = new int[answers.length];
        int[] answer3 = new int[answers.length];

        for(int i = 0; i < answers.length; i++){
            answer1[i] = stu1[i % 5];
            answer2[i] = stu2[i % 8];
            answer3[i] = stu3[i % 10];
        }


        for(int i = 0; i < answers.length; i++){
            if(answers[i] == answer1[i]){
                score1 = score1 + 1;
            }

            if(answers[i] == answer2[i]){
                score2 = score2 + 1;
            }

            if(answers[i] == answer3[i]){
                score3 = score3 + 1;
            }
        }

        List<Score> scores = new ArrayList<>();
        scores.add(new Score(1, score1));
        scores.add(new Score(2, score2));
        scores.add(new Score(3, score3));

        // DESC
        List<Score> finalScore = scores.stream()
                .sorted((a, b) -> b.score - a.score)
                .collect(Collectors.toList());

//        // ASC
//        List<Score> finalScore = scores.stream()
//                .sorted((a, b) -> a.score - b.score)
//                .collect(Collectors.toList());

        System.out.println(finalScore);

        List<Integer> list = new ArrayList<>();
        list.add(finalScore.get(0).number);

        if(finalScore.get(0).score == finalScore.get(1).score){
            list.add(finalScore.get(1).number);
        }
        if(finalScore.get(0).score == finalScore.get(2).score){
            list.add(finalScore.get(2).number);
        }

        Collections.sort(list);

        int[] answer = new int[list.size()];
        for(int j = 0; j < list.size(); j++){
            answer[j] = list.get(j);
        }

        return answer;
    }
    public class Score {
        private int number;
        private int score;

        public Score(int number, int score) {
            this.number = number;
            this.score = score;
        }
    }
    public static void main(String[] args){
        Solution T = new Solution();

        int[] answers = new int[]{1, 3, 2, 4, 2};

        for(int x :T.solution(answers)) System.out.print(x+" ");
    }
}

 

상당히 복잡하게 풀었다.

반성중.

반응형