[프로그래머스] 프린터 (javascript)

728x90
반응형

2021. 03. 31 업데이트된 풀이 

 

그냥 인덱스 위치를 담은 배열을 새로 만든다음에 비교해주면 된다. 기존 배열을 변형시킬 필요 없다.

function solution(priorities, location) {
    var answer = 0;
  
    const q=Array(priorities.length).fill(0).map((_,i)=>i);
    while(q.length>0){
        let max=Math.max(...priorities);
        let x=q.shift();
        if(priorities[x]<max){
            q.push(x);
        }else{
            answer+=1;
            if(x===location)break;
            priorities[x]=-1;
        }
        
    }
    return answer;
}

---

풀이 1 

function solution(priorities, location) {
    var answer = 0;
    const sorted_prior=[...priorities].sort((a,b)=>b-a);
    const sequence=[];
   let idx=0;
    while(priorities){
        // console.log(idx)
      if(priorities[idx]!==sorted_prior[0]){
          idx=(idx+1)%priorities.length;
      }else if(idx!=location){
          priorities[idx]=-1;
          sorted_prior.shift();
          answer+=1;
      }else{
          answer+=1;
          break;
      }
   }
    return answer;
}

풀이 2. some 메소드를 써봤다.

 

function solution(priorities, location) {
    const answer = [];
    const new_list=priorities.map((prior,idx)=>{
        return {
            prior,
            idx
        }
    });
    let cnt=0;

    while(new_list.length>0){
        const cur=new_list.shift();
        if(new_list.some(item=>item.prior>cur.prior)){
            new_list.push(cur);     
        }else {
            cnt+=1;
            if(cur.idx===location)return cnt;
        }
        
    }
    // return answer.findIndex(item=>item.idx===location)+1;
}
728x90
반응형
TAGS.

Comments