문제 풀기/C#

92. 프로세스

kagan-draca 2025. 3. 14. 14:50

 

기본 틀 :

using System;

public class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        return answer;
    }
}

 

문제를 제대로 이해하지 못 한 상태에서 예시 입출력에 한에서만 맞게 코드를 작성한 결과...

 

using System;
using System.Linq;
using System.Collections.Generic;

public class Solution {
    public int solution(int[] priorities, int location) 
    {
        int want = priorities[location];
        Queue<int> process = new Queue<int>(priorities);
        int bigCount = priorities.Max();
        
        for(int i = 0; i < process.Count; i++)
        {
            int peek = process.Peek();
            if(bigCount == peek) break;
            process.Dequeue();
            process.Enqueue(peek);
            location = location - 1 < 0 ? process.Count - 1 : location - 1;
        }
        
        return location + 1;
    }
}

 

위와 같이 부분적인 테스트 통과만 할 수 있었다...

 

문제의 핵심은

 

[3, 2, 4, 2, 1]

 

과 같이 우선 순위가 있는 프로세스가 있을 때

 

[3, 2, 4, 2, 1] -> [2, 4, 2, 1, 3]

(우선 순위가 높은 프로세스 아니라서 왼쪽으로 회전)

 

[2, 4, 2, 1, 3] -> [4, 2, 1, 3, 2]
(우선 순위가 높은 프로세스 아니라서 왼쪽으로 회전)

 

[4, 2, 1, 3, 2] -> [2, 1, 3, 2]
(우선 순위가 가장 높은 프로세스 실행)

 

[2, 1, 3, 2] -> [1, 3, 2, 2]

(우선 순위가 높은 프로세스 아니라서 왼쪽으로 회전)

 

[1, 3, 2, 2] -> [3, 2, 2, 1]

(우선 순위가 높은 프로세스 아니라서 왼쪽으로 회전)

 

[3, 2, 2, 1] -> [2, 2, 1]

(우선 순위가 가장 높은 프로세스 실행)

 

[2, 2, 1] -> [2, 1]

(우선 순위가 가장 높은 프로세스 실행)

 

[2, 1] -> [1]

(우선 순위가 가장 높은 프로세스 실행)

 

[1] -> []

(우선 순위가 가장 높은 프로세스 실행)

 

과 같이 현재 Queue의 가장 앞에 있는 프로세스가 우선 순위가 가장 높지 않을 경우

 

Queue에 다시 담는 과정을 반복한다.

 

그래서, 위와 같은 과정을 코드로 작성하면

 

아래의 코드가 작성된다.

(예시만 고려한 코드는 처음 가장 우선 순위만 고려하는 코드...)

using System;
using System.Linq;
using System.Collections.Generic;

public class Solution {
    public int solution(int[] priorities, int location) 
    {
        int answer = 0;
        Queue<int> process = new Queue<int>(priorities);
        
        while(process.Count != 0)
        {
            int max = process.Max();
            int dequeue = process.Dequeue();
            
            if(max != dequeue) process.Enqueue(dequeue);
            else
            {
                answer++;
                if(location == 0) break;
            }
            
            location = location - 1 < 0 ? process.Count - 1 : location - 1;
        }
        
        return answer;
    }
}

'문제 풀기 > C#' 카테고리의 다른 글

94. 타겟 넘버  (0) 2025.03.18
93. 피로도  (0) 2025.03.14
91. 기능 개발  (0) 2025.03.12
90. 의상  (0) 2025.03.12
89. 할인 행사  (0) 2025.03.11