[Programmers] 프로세스

밀크야살빼자·2023년 11월 2일
0
post-thumbnail

문제

운영체제의 역할 중 하나는 컴퓨터 시스템의 자원을 효율적으로 관리하는 것입니다. 이 문제에서는 운영체제가 다음 규칙에 따라 프로세스를 관리할 경우 특정 프로세스가 몇 번째로 실행되는지 알아내면 됩니다.

  1. 실행 대기 큐(Queue)에서 대기중인 프로세스 하나를 꺼냅니다.
  2. 큐에 대기중인 프로세스 중 우선순위가 더 높은 프로세스가 있다면 방금 꺼낸 프로세스를 다시 큐에 넣습니다.
  3. 만약 그런 프로세스가 없다면 방금 꺼낸 프로세스를 실행합니다.
    3.1 한 번 실행한 프로세스는 다시 큐에 넣지 않고 그대로 종료됩니다.

예를 들어 프로세스 4개 [A, B, C, D]가 순서대로 실행 대기 큐에 들어있고, 우선순위가 [2, 1, 3, 2]라면 [C, D, A, B] 순으로 실행하게 됩니다.

현재 실행 대기 큐(Queue)에 있는 프로세스의 중요도가 순서대로 담긴 배열 priorities와, 몇 번째로 실행되는지 알고싶은 프로세스의 위치를 알려주는 location이 매개변수로 주어질 때, 해당 프로세스가 몇 번째로 실행되는지 return 하도록 solution 함수를 작성해주세요.

제한사항

  • priorities의 길이는 1 이상 100 이하입니다.
    • priorities의 원소는 1 이상 9 이하의 정수입니다.
    • priorities의 원소는 우선순위를 나타내며 숫자가 클 수록 우선순위가 높습니다.
  • location은 0 이상 (대기 큐에 있는 프로세스 수 - 1) 이하의 값을 가집니다.
    • priorities의 가장 앞에 있으면 0, 두 번째에 있으면 1 … 과 같이 표현합니다.

입출력 예 설명

❌첫 번째 실패 코드❌

import java.util.*;
class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> Integer.compare(b[0], a[0]));
        
        for (int i = 0; i < priorities.length; i++) {
            queue.add(new int[]{priorities[i], i});
        }
                                                                                           
        for (int i = 1; i <= priorities.length; i++) {
            int[] element = queue.poll();
            if (element[1] == location) {
                answer = i;
                break;
            }
        }
        return answer;
    }
    
}

실패 이유를 모르겠어서 GPT한테 물어보니 PriorityQueue를 사용해서 정렬의 정확도가 떨어져서 테스트가 실패 뜬다고 알려줬다.

그래서 PriorityQueue로 reverse 정렬한 큐와 정렬 안한 큐 두개를 비교해서 두 값이 같을때는 ++해주고 location은 --해줬다.

✅ 성공한 코드

import java.util.*;
class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        PriorityQueue<Integer> prioritiesQueue = new PriorityQueue<>(Collections.reverseOrder());
        Queue<Integer> orderQueue = new LinkedList<>();
        
        for (int i = 0; i < priorities.length; i++) {
            prioritiesQueue.add(priorities[i]);
            orderQueue.add(priorities[i]);
        }
        
        while(!orderQueue.isEmpty()){
        int current = orderQueue.poll();
        int max = prioritiesQueue.peek();
        
            if(current==max){
                answer++;
                prioritiesQueue.poll();
                
                if(location==0) break;
            }else{
                orderQueue.add(current);
            }
            location--;
            if (location < 0) {
                location = orderQueue.size() - 1;
            }
        }
        return answer;
    }
    
}

Github

profile
기록기록기록기록기록

0개의 댓글