프린터 -프로그래머스(with Queue)

자몽·2022년 1월 6일
1

알고리즘

목록 보기
21/31
post-thumbnail

프린터(프로그래머스-queue)

문제 링크

https://programmers.co.kr/learn/courses/30/lessons/42587

설명

  • 테스트케이스

ex) priorities = [2,1,3,2]가 파라미터로 들어오면, 아래와 같이 객체를 배열에 저장시킨다.

priorities = [
  {index:0, priority: 2},
  {index:1, priority: 1},
  {index:2, priority: 3},
  {index:3, priority: 2}
  ]

만약, queue의 가장 앞에 있는 우선순위(priority)가 나머지의 우선순위보다 크다면, answer를 증가시켜주고,
그렇지 않다면 queue의 젤 뒤로 자리를 옮겨준다.

가장 앞에 있는 문서의 우선순위가 젤 클 때, 해당 문서는 출력되는데,
만약 location값과 일치하면 while 문을 중단시키고 answer(몇 번째로 인쇄되는지)를 return한다.

코드

function solution(priorities, location) {
    let answer = 0;
    let queue = []
    priorities.forEach((t,i)=>{
        queue.push({index:i,priority: t})
    })

    while(queue.length>0){
        let docx = queue.shift();
        if(queue.find(p => p.priority>docx.priority)){
            queue.push(docx);
        }else{
            answer++;
            if(docx.index ===location){
               return answer;
            }
        }
    } 
}
profile
꾸준하게 공부하기

0개의 댓글