우당탕탕 개발일지

[프로그래머스] 프로세스 (Java, Level.2) 본문

코테/프로그래머스

[프로그래머스] 프로세스 (Java, Level.2)

ujin302 2025. 2. 4. 16:51
반응형

문제

 

입출력 예시

풀이

 

 

머리로 잘 그려지지 않아서 엑셀에 표현해봄!

나는 프로세스명을 '인덱스P'로 표현하였고 큐에 저장함

 

currentIndex: 프로세스명에서 추출

currentProcess: 실행할 프로세스

currentPrioiry: 프로세스의 우선순위

maxPriority: 최고 우선순위

 

 

 

 

 

 

 

 

 

현재 프로세스의 우선순위보다 더 높은 프로세스가 있다고 판단

>> 큐에 해당 프로세스 add()

문제에서 제시한 2번에 해당하는 내용!

 

현재 프로세스가 가장 높은 우선순위임!

answer은 프로세스가 실행한 순서를 의미하기에 +1

 

현재 실행한 프로세스가 문제에서 원하는 값일 경우에 반환

그렇지 않으면 우선순위 재설정함(남아있는 프로세스 중에서 최고 우선순위 값 저장)

문제에서 제시한 3번에 해당하는 내용!

 

 

최종 코드

public int s6(int[] priorities, int location) {
        System.out.println("프로세스");
        int answer = 0;
        int proCount = priorities.length; // 프로세스 개수수
        Queue<String> proQueue = new LinkedList<>(); // 실행 대기 큐
        for (int i = 0; i < proCount; i++) {
            proQueue.add(i + "P");
        }

        // 최고 우선순위
        int maxPriority = Arrays.stream(priorities).max().orElse(0);

        while (true) {
            String currentProcess = proQueue.poll(); // 현재 프로세스
            int currentIndex = Integer.parseInt(currentProcess.replace("P", "")); // 현재 프로세스 인덱스 번호
            int currentPrioiry = priorities[currentIndex]; // 현재 프로세스 우선순위

            if (currentPrioiry < maxPriority) {
                // 다시 큐에 저장
                proQueue.add(currentProcess);

            } else {
                answer++; // 실행한 프로세스 개수
                if (currentProcess.equals(location + "P"))
                    return answer;

                // 최고 우선순위 재설정
                if (currentPrioiry == maxPriority) {
                    priorities[currentIndex] = 0;
                    maxPriority = Arrays.stream(priorities).max().orElse(0);
                }
            }
        }
    }

 

 

 

프로그래머스 문제

https://school.programmers.co.kr/learn/courses/30/lessons/42587#

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

반응형