[프로그래머스] 모의고사 (Level 1)

유진·2024년 7월 26일
0

코딩테스트

목록 보기
11/18

📝 모의고사 (Level 1)

완전탐색
모의고사

🔹Python

  • 나의 풀이 (다른 사람 아이디어 참고)
def solution(answers):
    answer = []
    
    person1 = [1, 2, 3, 4, 5]
    person2 = [2, 1, 2, 3, 2, 4, 2, 5]
    person3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
    
    count1 = 0
    count2 = 0
    count3 = 0
    
    for i in range(len(answers)):
        if answers[i] == person1[i % len(person1)]:
            count1 += 1
        if answers[i] == person2[i % len(person2)]:
            count2 += 1
        if answers[i] == person3[i % len(person3)]:
            count3 += 1
            
    tmp = [count1, count2, count3]
    max_count = max(tmp)  
    
    for i, score in enumerate(tmp):
        if score == max_count:
            answer.append(i + 1) 

    return answer

answers의 인덱스/각 리스트 사이즈 한 값을 인덱스로 넣어주면 list에 해당하는 값이 반복적으로 나오게 할 수 있다. 이걸 어떻게 표현할지 모르겠어서 계속 고민했다. 이런 패턴은 자주 등장 할 거 같으니 꼭 알아둬야 겠다.

  • 다른 사람의 풀이
def solution(answers):
    pattern1 = [1,2,3,4,5]
    pattern2 = [2,1,2,3,2,4,2,5]
    pattern3 = [3,3,1,1,2,2,4,4,5,5]
    score = [0, 0, 0]
    result = []

    for idx, answer in enumerate(answers):
        if answer == pattern1[idx%len(pattern1)]:
            score[0] += 1
        if answer == pattern2[idx%len(pattern2)]:
            score[1] += 1
        if answer == pattern3[idx%len(pattern3)]:
            score[2] += 1

    for idx, s in enumerate(score):
        if s == max(score):
            result.append(idx+1)

    return result

count 변수를 각각 선언하지 말고 score 배열을 만들어서 저장하는 것이 훨씬 효율적이다.


🔸Java

  • 나의 풀이
import java.util.ArrayList;
import java.util.List;

class Solution {
    public int[] solution(int[] answers) {
        List<Integer> result = new ArrayList<>();
        int[] pattern1 = {1, 2, 3, 4, 5};
        int[] pattern2 = {2, 1, 2, 3, 2, 4, 2, 5};
        int[] pattern3 = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
        
        int[] score = new int[3];
        
        for (int i = 0; i < answers.length; i++) {
            if (answers[i] == pattern1[i % pattern1.length]) {
                score[0] += 1;
            }
            if (answers[i] == pattern2[i % pattern2.length]) {
                score[1] += 1;
            }
            if (answers[i] == pattern3[i % pattern3.length]) {
                score[2] += 1;
            }
        }
        
        // 최댓값 초기화
        int maxScore = score[0];

        // 배열을 순회하면서 최댓값 찾기
        for (int i = 1; i < score.length; i++) {
            if (score[i] > maxScore) {
                maxScore = score[i];
            }
        }
        
        // 최댓값의 인덱스 찾기
        for (int idx = 0; idx < score.length; idx++) {
            if (score[idx] == maxScore) {
                result.add(idx + 1);
            }
        }
  
        // List를 int[] 배열로 변환
        int[] answer = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            answer[i] = result.get(i);
        }
        
        return answer;
    }
}

인덱스 구하는 부분 음.. 너무 길어졌는데 어쩔 수 없는듯

int maxScore = Math.max(score[0], score[1], score[2]);
처음에 이렇게 작성했는데 Math.max() 메서드는 두 개의 인수를 비교하는 메서드라 세 개 이상의 값을 한 번에 비교할 수 없다고 한다. 그래서 저렇게 반복문으로 처리했다.

  • 다른 사람의 풀이
import java.util.ArrayList;

class Solution {
    public int[] solution(int[] answer) {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = {2, 1, 2, 3, 2, 4, 2, 5};
        int[] c = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
        int[] score = new int[3];
        for(int i=0; i<answer.length; i++) {
            if(answer[i] == a[i%a.length]) {score[0]++;}
            if(answer[i] == b[i%b.length]) {score[1]++;}
            if(answer[i] == c[i%c.length]) {score[2]++;}
        }
        int maxScore = Math.max(score[0], Math.max(score[1], score[2]));
        ArrayList<Integer> list = new ArrayList<>();
        if(maxScore == score[0]) {list.add(1);}
        if(maxScore == score[1]) {list.add(2);}
        if(maxScore == score[2]) {list.add(3);}
        return list.stream().mapToInt(i->i.intValue()).toArray();
    }
}

Math.max를 이중으로 써서 score 3개를 비교했다. 그리고 ArrayList를 사용해서 마찬가지로 인덱스를 넣어줬는데 List를 Array로 바꾸는 것을 stream을 이용해서 한 줄로 처리해줬다.

📢 list.stream().mapToInt(i->i.intValue()).toArray(); 📢

list라는 정수형 리스트를 생성하고, 이를 스트림으로 변환하여 mapToInt() 메서드를 이용해 각 요소를 int 형으로 매핑한 후 toArray() 메서드를 사용하여 int 배열로 변환하고 있습니다.

mapToInt(Integer::intValue)은 각 Integer 객체를 int 값으로 변환합니다.
toArray()는 스트림의 요소들을 배열로 반환합니다.


Q. ✅ 그럼 Integer랑 int랑 다른거야?

네, Integer와 int는 자바에서 서로 다른 데이터 타입입니다.

int: 기본 데이터 타입(primitive type) 중 하나로, 정수 값을 저장하는 데 사용됩니다. int는 32비트의 부호 있는 정수를 표현할 수 있으며, 기본값은 0입니다. 예를 들어, int x = 10;과 같이 사용합니다.

Integer: int의 래퍼 클래스(wrapper class)로, 정수 값을 객체로 감싸고 여러 유틸리티 메서드를 제공합니다. Integer 클래스는 int 값을 포장하여 객체로 만들어 주는 역할을 합니다. 예를 들어, Integer x = 10;과 같이 사용합니다.

주요 차이점은 다음과 같습니다:

  • Null 값 처리: int는 기본 데이터 타입이므로 null 값을 가질 수 없지만, Integer는 객체이기 때문에 null을 가질 수 있습니다.
  • 메서드 호출: int는 메서드를 호출할 수 없고, Integer는 객체이므로 메서드를 호출할 수 있습니다. 예를 들어, Integer 클래스는 parseInt() 메서드를 통해 문자열을 정수로 변환할 수 있습니다.
  • 박싱(Boxing)과 언박싱(Unboxing): Integer는 int 값으로의 변환(언박싱)과 반대로 int를 Integer 객체로의 변환(박싱)을 지원합니다.

따라서, 프로그래밍에서는 주로 기본 데이터 타입 int를 사용하고, 필요에 따라 Integer 클래스를 사용하여 객체로 처리해야 하는 경우가 있습니다. 예를 들어, 컬렉션 프레임워크에서는 기본적으로 객체만 저장할 수 있기 때문에 Integer를 사용해야 할 때가 많습니다.

profile
유진진입니덩

0개의 댓글