관리 메뉴

bright jazz music

프로세스 본문

Algorithm Practice/프로그래머스

프로세스

bright jazz music 2026. 1. 27. 22:55
function solution(priorities, location) {
    // 인덱스를 함께 저장 (어떤 프로세스인지 추적)
    let queue = priorities.map((priority, index) => ({
        priority,
        index
    }));
    
    let executionOrder = 0;
    
    while (queue.length > 0) {
        const current = queue.shift(); // 큐에서 하나 꺼냄
        
        // 큐에 현재보다 높은 우선순위가 있는지 확인
        if (queue.some(item => item.priority > current.priority)) {
            // 있으면 다시 뒤로 보냄
            queue.push(current);
        } else {
            // 없으면 실행
            executionOrder++;
            
            // 찾던 프로세스면 반환
            if (current.index === location) {
                return executionOrder;
            }
        }
    }
}
```

## 왜 당신 코드가 틀렸나

테스트 2를 보면:
- `[1, 1, 9, 1, 1, 1]`, location=0
- 당신 코드는 0번 프로세스(우선순위 1)보다 큰 게 1개(9)니까 answer=2 반환
- 실제로는: 9가 먼저 실행되고, 그 다음 나머지 1들이 순서대로 실행되므로 0번은 **5번째**

큐 동작을 무시하고 단순 카운팅만 했기 때문입니다.

## 동작 과정 (테스트 2)
```
초기: [(1,0), (1,1), (9,2), (1,3), (1,4), (1,5)]

1. (1,0) 꺼냄 → 9가 더 크니 뒤로: [(1,1), (9,2), (1,3), (1,4), (1,5), (1,0)]
2. (1,1) 꺼냄 → 9가 더 크니 뒤로: [(9,2), (1,3), (1,4), (1,5), (1,0), (1,1)]
3. (9,2) 꺼냄 → 최고 우선순위 → 실행! (1번째)
4. (1,3) 꺼냄 → 다 같으니 → 실행! (2번째)
5. (1,4) 꺼냄 → 실행! (3번째)
6. (1,5) 꺼냄 → 실행! (4번째)
7. (1,0) 꺼냄 → 실행! (5번째) ← location=0 찾음!

'Algorithm Practice > 프로그래머스' 카테고리의 다른 글

올바른 괄호  (0) 2026.01.26
의상  (1) 2026.01.22
전화번호 목록  (0) 2026.01.21
같은 숫자는 싫어  (0) 2026.01.20
폰켓몬  (0) 2026.01.19
Comments