[알고리즘 문제풀이] 프로그래머스 - 모의고사

yourjin·2022년 2월 27일
0

알고리즘 문제풀이

목록 보기
9/28
post-thumbnail

TIL (2022.02.13)

➕ 오늘 푼 문제


프로그래머스 - 모의고사

➕ 아이디어


  • 각 학생들의 문제를 찍는 최소 패턴을 찾아, 그 패턴을 계속 반복한다.
    • 여기서는 최소 패턴의 길이의 나머지 값을 해당 문제에서 찍은 번호의 인덱스로 삼는다.
  • 각 학생별로 점수를 구한다.
  • 최대 점수를 가지는 학생들을 오름차순으로 정렬하여 반환한다.

➕ Java 코드


import java.util.*;

class Solution {
    public int[] solution(int[] answers) {
        List<Integer> answer = new ArrayList<Integer>();
        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[] scores = {0, 0, 0};
        
        for(int i=0; i<3; i++){
            for(int j=0; j<answers.length; j++){
                int n = patterns[i].length;
                if(answers[j] == patterns[i][j%n]){
                    scores[i] += 1;    
                }
            }
        }
    
        int maxScore = 0;
        for(int score : scores){
            maxScore = Math.max(maxScore, score);
        }
        
        for(int i=0; i<3; i++){
            if(scores[i] == maxScore){
                answer.add(i+1);
            }
        }
        
        return answer.stream().mapToInt(i->i).toArray();
    }
}

➕ Python 코드


def solution(answers):
    answer = []
    patterns = [[1, 2, 3, 4, 5],
                [2, 1, 2, 3, 2, 4, 2, 5],
                [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]]
    scores = [0, 0, 0]
    
    for i in range(3):
        for j in range(len(answers)):
            if answers[j] == patterns[i][j%len(patterns[i])]:
                scores[i] += 1
    
    max_value = max(scores)
    for i in range(3):
        if max_value == scores[i]:
            answer.append(i+1)
    
    return answer

➕ 궁금한 내용 및 소감


  • 아이디어 자체는 간단했으나, 나에게는 자바로 구현하기 조금 까다로운 문제였다. 특히, answer를 int 배열로 반환하기 위해 List에서 배열로 반환을 해야 한다던가, 배열에서 최대 값을 찾기 위해 반복문을 돌려야 하는 부분은 문법이 익숙치 않아 번거로웠다. 자주 사용하며 손에 익을 수 있도록 노력해야겠다.

➕ 참고 문헌


  • Java - List ↔ int[]
    • reference type(ex. String)의 경우, List의 toArray() 메소드를 통해 배열로 변환 가능하다.
    • primitive type(ex. int)의 경우, 위와 같이 할 수 없다. 따라서 직접 반복문을 돌며 배열을 생성하거나, stream을 통해 int 타입으로 변환한 후 toArray() 메소드를 사용해 변환 가능하다.
      // 방법 1
      int[] arr1 = new int[list.size()]
      for (int i = 0 ; i < list.size() ; i++) {
           arr1[i] = list.get(i).intValue();   
      }
      
      // 방법 2
      int[] arr2 = list.stream()
      	                .mapToInt(i -> i)
      	                .toArray();
          
      // 방법 3
      int[] arr3 = list.stream()
      	                .mapToInt(Integer::intValue)
      	                .toArray();
      
      // 방법 4
      int[] arr4 = list.stream()
      	                .filter(i -> i != null)
      	                .mapToInt(i -> i)
      	                .toArray();
    • 참고 링크: [Java] Integer ArrayList을 int 배열로 변환 방법
  • Java - 배열에서 최댓값 구하기
profile
make it mine, make it yours

0개의 댓글