코딩테스트/Programmers

[프로그래머스] PCCE 기출문제 10번 / 데이터 분석

grove1212 2025. 1. 26. 20:47
  1. 소요 시간 : 40분
  2. 배운 점
    • sorted에 커스텀 comparator 적용하는 법
      음수면 a가 앞에, 양수면 b가 앞에 오는 방식이다. 그래서 오른쪽에 식을 작성할 때 어떤걸 앞에 두고싶은지 생각해서 음수로 나오게할지, 양수로 나오게 할지 결정하면 된다.
      • 오름차순
        `(a, b) -> a - b`
        a - b가 음수일 때는 a가 작을 때이다. a가 작을 때 a가 앞에 있으니 오름차순이다.
      • 내림차순
        `(a, b) -> b - a`
        b - a가 음수일 때는 a가 클 떄이다. a가 클 때 a가 앞에 있으니 내림차순이다.
  • toArray에 원하는 형태로 바꾸는 법
    toArray(원하는데이터형::new)
  1. 본인 코드
import java.util.stream.*;
import java.util.Arrays;

class Solution {
    public int[][] solution(int[][] data, String ext, int val_ext, String sort_by) {
        int filter_col = getColIdx(ext);
        int sort_col = getColIdx(sort_by);

        int[][] answer = Arrays.stream(data)
            .filter(row -> row[filter_col] < val_ext)
            .sorted((a, b) -> a[sort_col] - b[sort_col])
            .toArray(int[][]::new);

        return answer;
    }

    int getColIdx(String ext){
        int result;
        if(ext.equals("code")) result = 0;
        else if(ext.equals("date")) result = 1;
        else if(ext.equals("maximum")) result = 2;
        else result = 3;
        return result;
    }
}