[프로그래머스] 프로세스

Gaanii·2025년 3월 5일
0

Problem Solving

목록 보기
176/210
post-thumbnail

아래 프로그래머스 로고를 클릭하면 해당 문제로 이동합니다 😀

프로그래머스로고



풀이과정


any/all에 대해 망각하고 있다가 다시 기억을 꺼내와서 블로깅 ..

파라미터는 iterable한 객체를 삽입해야한다.
any: 하나라도 True라면 return True
all: 모두 True라면 return True

location에 몇번째로 실행되는지 알고싶은 프로세스의 위치가 주어지기 때문에 enumerate로 (인덱스,프로세스) 튜플 리스트를 생성하고 이를 조건문에 걸어 사용하면 된다.


만약 큐에있는 프로세스 중 하나라도 현재 프로세스보다 우선순위가 높다면 현재 프로세스는 다시 큐로 넣어주고,

그게 아니라면 처리된 프로세스의 개수인 cnt를 늘리고, 방금 처리된 프로세스(현재 프로세스)가 내가 찾고자하는 프로세스였다면 처리된 프로세스의 개수인 cnt를 리턴해주면 된다.


코드


1. Python

from collections import deque

def solution(priorities, location):
    queue = deque((idx, pro) for idx, pro in enumerate(priorities))
    cnt = 0

    while True:
        current = queue.popleft()
        if any(current[1] < q[1] for q in queue):
            queue.append(current)
        else:
            cnt += 1
            if current[0] == location:
                return cnt

print(solution([2, 1, 3, 2], 2))
print(solution([1, 1, 9, 1, 1, 1], 0))

2. Js

function solution(priorities, location) {
    var answer = 0;
    let queue = priorities.map((v, i) => [v, i]);
    
    while(queue){
        let popElement = queue.shift();
        if(queue.some(v => v[0] > popElement[0])){
            queue.push(popElement);
        } else {
            answer++;
            if(popElement[1] === location) return answer;
        }
    }
    return answer;
}


결과


0개의 댓글