만족은 하되 안주하지는 말자

기록해야 기억한다

프로그래밍/programmers&bj

[JAVA] 기능개발

D36choi 2022. 2. 9. 17:25
728x90

문제

https://programmers.co.kr/learn/courses/30/lessons/42586?language=java# 

 

코딩테스트 연습 - 기능개발

프로그래머스 팀에서는 기능 개선 작업을 수행 중입니다. 각 기능은 진도가 100%일 때 서비스에 반영할 수 있습니다. 또, 각 기능의 개발속도는 모두 다르기 때문에 뒤에 있는 기능이 앞에 있는

programmers.co.kr

분류는 스택/큐

내 풀이

간단한 날짜 계산과 큐를 이용해 풀어야하는 문제.

꼭 큐가 필요하진 않지만 나는 분류대로 자료구조 이용해 풀어야겠다.

import java.util.Queue;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;

class Solution {
    public int[] solution(int[] progresses, int[] speeds) {
        List<Integer> answers = new ArrayList<Integer>();
        Queue<Integer> line = new LinkedList<Integer>();
        for (int i=0; i<progresses.length; i++) {
            line.offer(this.getWorkday(progresses[i], speeds[i]));
        }
        
        while(!line.isEmpty()) {
            int count = 1;
            int first = line.poll();
            while (line.peek() != null) {
                if(line.peek() <= first) {
                    line.poll();
                    count++;
                } else {
                    break;
                }
            }
            answers.add(count);
        }
        
        return answers.stream().mapToInt(i -> i).toArray();
    }
    
    private Integer getWorkday(int progress, int speed) {
        Integer day = (100-progress) / speed;
        
        return (100-progress) % speed > 0 ? day+1 : day;
    }
}

 

알게 된 것

1. Queue나 stack의 null pointer exception을 방지하도록 하는게 중요

2. queue의 peek(), offer(), element() 등의 메서드를 알게되었다

 NPE을 내냐, null을 리턴하느냐의 차이로 같은 기능이어도 return이 다른 메서드들이 존재한다.

 

https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html

 

Queue (Java Platform SE 8 )

A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the opera

docs.oracle.com

사실 내가 자바로 큐를 써본 경험은 없는 듯하다. 큐나 스택은 비어있을때 보통 루프를 벗어나야하기때문에 이걸 어떻게 하면 우아하게 코드를 작성할 수 있을 지 고민해야겠다.

저 코드상으로 while문과 if문의 중첩은 가독성이 떨어져보인다.

 

3. 원시자료형 array 를 조작하는데에 어려움을 느꼈다. `new Int[] {}` 는 배열의 초기화와 동시에 값을 할당하는 것.

https://stackoverflow.com/questions/9114047/curly-braces-when-define-array

 

curly braces when define array

Regards to the following code: int[] to = new int[] { text }; I understand it tries to define an array of integer, but What does the curly braces do in array definition?

stackoverflow.com

 

4. answer 배열은 길이가 동적인 케이스가 많으니 그냥 처음엔 List형태로 시작하고 나중에 원시자료형 array로 변경하자

List.stream().mapToInt(i->i).toArray();

피드백

NPE을 잘 벗어나도록 메서드들을 암기해놔야 한다. (많이하면 외워지겠지)

 

array와 List 를 오가는 java stream 스킬들을 배워두면 편하고 아름다울 것 같다.

 

100초과 계산식은 아래처럼 해도 가능하다. 내꺼도 나쁘진 않지만 이게 덜 복잡하다.

while(progresses[i] + (day*speeds[i]) < 100) {
                day++;
            }
            dayOfend[day]++;