프린터 ( 큐 ) 알고리즘

woobaeh·2022년 3월 4일
0

Algorithm

목록 보기
4/7
function queuePrinter(bufferSize, capacities, documents) {
              // Input :  2    ,    10     , [7,4,5,6]
  let time = 1; // 걸린 시간(초)
  let queue = []; // 문서가 들어갈 인쇄작업 목록
  let totalBufferVolume = 0; // 작업 목록의 총 용량
  // queue에 bufferSize만큼 0을 삽입 (queue에 들어갈 수 있는 목록의 숫자)
    for(let i = 0; i < bufferSize; i++){
        queue.push(0);     // queue = [0, 0]
    }

  let currentDocument = documents.shift(); // 7   documents [4,5,6]
  queue.unshift(currentDocument); // queue [7, 0, 0]
  queue.pop(); // 이는 작업 목록의 숫자를 유지 queue [7, 0]
  totalBufferVolume += currentDocument; // 7

  // 여기까지가 1초 일 때

  // 용량이 0이 될때까지 곧 인쇄 다 할 때까지 매초마다 !
  while (totalBufferVolume) {

  // 총 용량) queue의 마지막 배열을 빼주면서 용량도 빼준다..  ? 작업 목록에서 빠질 꺼니까
    totalBufferVolume -= queue.pop(); //  2초: queue [0,7] 3초: [0,0] 4초: [4] 5초:[5]
  // document의 맨 앞의 요소를 일단 빼고, 현재 문서로 저장한다.
    currentDocument = documents.shift(); // 2초 : curDoc = 4 doc = [5,6] 3초: curDoc = 4, doc = [5,6]
  // 여기서 용량에 따라서 분기점이 생긴다.        // 4초 : curDoc = 5 doc = [6] 5초: cur 6, doc []
  // 만약 여유공간이 있다면
    if (currentDocument + totalBufferVolume <= capacities) { // 2초 :7 + 4이라 if문 패스 5초 5 + 11 이라 패스
    // queue에 currentDocument 삽입 후 총 용량에 현재 문서의 용량을 더해준다.
      queue.unshift(currentDocument); // 3초: [4,0] , 4초 [5,4]
      totalBufferVolume += currentDocument; // 3초: 4         4초: 9
    } else { // 용량이 모자른 경우
    // documents에 현재 문서를 맨 앞에 다시 넣어준다.(shift해준것을 다시 복구)
      documents.unshift(currentDocument); // doc = [4,1,5] doc = [6]
      queue.unshift(0);// 추가된 문서가 없기 때문에 맨 앞의 queue에 0을 추가 // 2초 [0, 7]  5초 [0,5] ....
    } //
    time++; // 1초씩 추가
  }
  return time;
}

🔑 천천히 코드를 파악하고 또 디버깅 해보면서 그림으로만 그렸던 큐가 어떻게 흘러가는지 이해할 수 있었다

profile
상생을 통하여 파이를 훨씬 크게 키울 수 있다. WIN - WIN

0개의 댓글