[프로그래머스] 과제 진행하기 JavaScript

·2025년 2월 12일

문제

과제를 받은 루는 다음과 같은 순서대로 과제를 하려고 계획을 세웠습니다.

  • 과제는 시작하기로 한 시각이 되면 시작합니다.
  • 새로운 과제를 시작할 시각이 되었을 때, 기존에 진행 중이던 과제가 있다면 진행 중이던 과제를 멈추고 새로운 과제를 시작합니다.
  • 진행중이던 과제를 끝냈을 때, 잠시 멈춘 과제가 있다면, 멈춰둔 과제를 이어서 진행합니다.
    • 만약, 과제를 끝낸 시각에 새로 시작해야 되는 과제와 잠시 멈춰둔 과제가 모두 있다면, 새로 시작해야 하는 과제부터 진행합니다.
  • 멈춰둔 과제가 여러 개일 경우, 가장 최근에 멈춘 과제부터 시작합니다.

과제 계획을 담은 이차원 문자열 배열 plans가 매개변수로 주어질 때, 과제를 끝낸 순서대로 이름을 배열에 담아 return 하는 solution 함수를 완성해주세요.

제한 사항

3 ≤ plans의 길이 ≤ 1,000

  • plans의 원소는 [name, start, playtime]의 구조로 이루어져 있습니다.
    • name : 과제의 이름을 의미합니다.
      - 2 ≤ name의 길이 ≤ 10
      - name은 알파벳 소문자로만 이루어져 있습니다.
      - name이 중복되는 원소는 없습니다.
    • start : 과제의 시작 시각을 나타냅니다.
      - "hh:mm"의 형태로 "00:00" ~ "23:59" 사이의 시간값만 들어가 있습니다.
      - 모든 과제의 시작 시각은 달라서 겹칠 일이 없습니다.
      - 과제는 "00:00" ... "23:59" 순으로 시작하면 됩니다. 즉, 시와 분의 값이 작을수록 더 빨리 시작한 과제입니다.
    • playtime : 과제를 마치는데 걸리는 시간을 의미하며, 단위는 분입니다.
      - 1 ≤ playtime ≤ 100
      - playtime은 0으로 시작하지 않습니다.
    • 배열은 시간순으로 정렬되어 있지 않을 수 있습니다.

진행중이던 과제가 끝나는 시각과 새로운 과제를 시작해야하는 시각이 같은 경우 진행중이던 과제는 끝난 것으로 판단합니다.

입력

plans : [["korean", "11:40", "30"], ["english", "12:10", "20"], ["math", "12:30", "40"]]

출력

["korean", "english", "math"]

내가 했던 풀이 방법

  1. 과제를 우선순위 큐(MinHeap)에 담아 시작시간 순으로 정렬해준다.
  2. currentTime을 가장 빠르게 시작하는 시간으로 저장해주고 current를 null로 ready를 빈배열로 초기화해준다. 여기서 current는 현재 진행하는 과제를 의미하고 ready는 도중에 중단되어 기다리는 과제들의 모음이다.
  3. 우선순위 큐에 과제가 존재할 때까지 다음 내용을 반복한다. 1) 만약 현재 current가 존재하지 않고 ready에 과제가 존재한다면 current를 ready로 바꿔준다. 2) 만약 current가 존재하지 않고 currentTime이 가장 빠르게 과제 시작시간보다 이전일 경우 currentTime을 가장 빠른 시작 시간으로 바꿔준다. 3) 만약 current가 존재한다면 남은 시간을 1 감소시켜준다. 이때 남은 시간이 0이 된다면 해당 과제는 끝난 것으로 판단하고 answer에 과제 이름을 push 해주고 current를 null로 비워준다. 4) 만약 현재 시간에 시작해야 하는 과제가 존재하면 해당 과제를 dequeue해서 current에 저장한다. 만약 current에 저장하기 전에 current가 존재하고 남은 시간이 존재할 경우, ready에 진행하던 과제를 push 해준다.
  4. 3번을 우선순위 큐가 비워질 때까지 반복하면 시작 시간에 무조건 시작해야 하는 과제들에 대한 처리가 끝난다. 즉, 앞으로 남은 과제들은 남은 시간이 끝날 때까지 변경되지 않고 끝낼 수 있다. current에 현재 과제가 존재한다면, 그 과제는 끝날 때까지 변경되지 않는다. 즉, 남은 과제중에 가장 먼저 끝난다. 이후로 ready에 들어간 과제들 중에 최근에 했던 과제 순서대로 과제를 진행하게 될 것이고 이것 또한 도중에 변경되지 않는다. 이들의 과목명을 push 해준다.

코드

function solution(plans) {
    var answer = [];
    
    class MinHeap {
        constructor() {
            this.heap = [null];
        }
        
        enqueue(value) {
            this.heap.push(value);
            let current = this.heap.length - 1;
            let parent = Math.floor(current / 2);
            
            while (parent > 0 && this.heap[current][1] < this.heap[parent][1]) {
                [this.heap[current], this.heap[parent]] = [this.heap[parent], this.heap[current]];
                current = parent;
                parent = Math.floor(current / 2);
            }
        }
        
        dequeue() {
            if (this.heap.length === 1) return null;
            if (this.heap.length === 2) return this.heap.pop();
            
            let result = this.heap[1];
            this.heap[1] = this.heap.pop();
            let current = 1;
            
            while (true) {
                let smallest = current;
                let left = 2 * current;
                let right = left + 1;
                
                if (left < this.heap.length && this.heap[left][1] < this.heap[smallest][1]) {
                    smallest = left;
                }
                if (right < this.heap.length && this.heap[right][1] < this.heap[smallest][1]) {
                    smallest = right;
                }
                
                if (smallest === current) break;
                [this.heap[current], this.heap[smallest]] = [this.heap[smallest], this.heap[current]];
                current = smallest;
            }
            return result;
        }
        
        peek() {
            if (this.heap.length === 1) return null;
            return this.heap[1];
        }
        
        getSize() {
            return this.heap.length - 1;
        }
    }
    
    let timePlan = new MinHeap();
    for (let i = 0; i < plans.length; i++) {
        let [name, start, playtime] = plans[i];
        start = start.split(":").map(Number);
        start = start[0] * 60 + start[1];
        timePlan.enqueue([name, start, Number(playtime)]);
    }

    let currentTime = timePlan.peek()[1];
    let current = null;
    let ready = [];
    
    while (timePlan.getSize()) {
        if (!current && ready.length > 0) {
            current = ready.pop();
        }
        
        if (!current && currentTime < timePlan.peek()[1]) {
            currentTime = timePlan.peek()[1];
        }
        
        if (current) {
            current[2]--;
            if (current[2] === 0) {
                answer.push(current[0]);
                current = null;
            }
        }
        
        while (timePlan.getSize() && currentTime === timePlan.peek()[1]) {
            if (current && current[2] > 0) {
                ready.push(current);
            }
            current = timePlan.dequeue();
        }
        currentTime++;
    }
    
    if (current) answer.push(current[0]);
    while (ready.length > 0) {
        answer.push(ready.pop()[0]);
    }
    return answer;
}

회고

ready에 들어간 문제를 큐로 받아들여서 왜... 테케가 저렇게 될까 고민을 한참했는데 문제를 또 대충 읽었다...ㅜ 그것만 아니면 생각보다 쉽게 풀린 문제 보통 그리디로 푼다고 하는데 최근 우선순위 큐를 많이 접해서 그런가 우선순위가 바로 생각났다.

profile
Frontend🍓

0개의 댓글