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

MandarinePunch·2022년 3월 6일
0

코딩 테스트

목록 보기
5/8
post-thumbnail

문제 설명


반복되는 배열을 쉽게 나타낼 수 있을 것 같은데, 뭔가... 노가다성 방법 말고는 생각이 나지 않았다. 그래서 생각하다 고안한 방법은 다음 설명과 같다! (다시 봐도 정말 이상한 방법이다 ㅋㅋ)

1. 배열을 반복할 수 없으므로 repeat를 쓸 수 있는 String으로 배열을 바꾼다.
2. 그 후 문자열의 길이가 답지 길이보다 작으면 정의한 함수만큼 반복 후 답지 길이와 같게 자른다.
3. 자른 문자열을 다시 String 배열로 바꾸고 int 배열로 형변환한다.
4. 답지와 배열을 비교 후 많이 맞춘 사람을 return한다.

최초 통과 코드

import java.util.*;

class Solution {
    public String repeatNum(String str, int len){
        return len > str.length() ? str.repeat(len/str.length() + 1) : str;
    }

    public int[] solution(int[] answers) {
        int len = answers.length;
        int count1=0, count2=0, count3=0;
        int[][] math = {
            {1,2,3,4,5},
            {2,1,2,3,2,4,2,5},
            {3,3,1,1,2,2,4,4,5,5}
        };

        for(int i=0;i<math.length;i++){
        	// 다시 봐도 웃긴 로직 ㅋㅋ
            String strMath = Arrays.toString(math[i]).replaceAll("[^0-9]","");
            String[] strArrMath = repeatNum(strMath, len).substring(0, len).split("");
            math[i] = Arrays.stream(strArrMath).mapToInt(Integer::parseInt).toArray();
        }

        for(int i=0;i<len;i++){
            if(answers[i] == math[0][i]) count1++;
            if(answers[i] == math[1][i]) count2++;
            if(answers[i] == math[2][i]) count3++;
        }

        List<Integer> list = new ArrayList<>();
        int maxNum = Math.max(count1, Math.max(count2, count3));
        if(maxNum == count1) list.add(1);
        if(maxNum == count2) list.add(2);
        if(maxNum == count3) list.add(3);

        return list.stream().mapToInt(e -> e).toArray();
    }
}

놀랍게도 런타임 에러가 뜨지 않고 통과한 코드이다. ㅋㅋㅋ
자바스크립트가 주 언어였다보니 생각하는 방식이 이상해서 이런 괴랄한 방식이 나온 것 같다.
(자바스크립트는 자료형 구분이 거의 없다시피 한다.)

통과 후 다른분의 코드를 보니... 코자타임이 와버렸다 ㅋㅋ

짱짱 코드

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]++;}
        }
        
        ArrayList<Integer> list = new ArrayList<>();
        int maxScore = Math.max(score[0], Math.max(score[1], score[2]));
        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();
    }
}

무작정 배열을 반복시킨 후 자를 생각만 했는데, 나머지 수식(%)을 사용할 줄은 몰랐다.
세상은 넓고 똑똑한 사람은 많은 것 같다.😂

profile
개발을 좋아하는 귤나라 사람입니다.

0개의 댓글