프로그래머스 : 프린터 ( 배열안의 객체 다루기 )

KHW·2021년 5월 1일
0

알고리즘

목록 보기
22/37

문제

100/100 (35분 소요)

기본적인 내용

  1. 인쇄 대기목록의 가장 앞에 있는 문서(J)를 대기목록에서 꺼냅니다.
  2. 나머지 인쇄 대기목록에서 J보다 중요도가 높은 문서가 한 개라도 존재하면 J를 대기목록의 가장 마지막에 넣습니다.
  3. 그렇지 않으면 J를 인쇄합니다.

대기목록을 반복해서 빼냈다 넣다를 반복진행하는 것을 주의한다.

내가 인쇄를 요청한 문서가 몇 번째로 인쇄되는지 => 넣다뺐다를 index에 주의해야한다.


배열에 객체넣기 ( 배열을 오름차순 정렬했을때의 인덱스 순서 찾기)

let index = [0,1,2,3,4]
let value = [8,4,1,3,9]
let result =[];


result =  value.map((x,i)=>({value:x , index : index[i]}));	// () 괄호 주의 !!!!!!!
// value.map((x,i)=>result.push({value:x , index : index[i]}));

console.log(result);

result.sort((a,b)=>a.value - b.value);

console.log(result);

result = ~~와
value.map(~)는 같은 결과를 나타낸다.

첫번째 console.log는
[
{ value: 8, index: 0 },
{ value: 4, index: 1 },
{ value: 1, index: 2 },
{ value: 3, index: 3 },
{ value: 9, index: 4 }
]

두번째 console.log는
[
{ value: 1, index: 2 },
{ value: 3, index: 3 },
{ value: 4, index: 1 },
{ value: 8, index: 0 },
{ value: 9, index: 4 }
]

객체를 통해 배열 오름차순 정렬이 index에서도 같이 적용된 것을 알 수 있다.


성공한 수정 전 코드

function solution(priorities, location) {
    let max;
    let result=[];
    let index = [];
    let num = 0;
    priorities.map((x,i)=>index.push(i));
    
    for(;priorities.length != 0 ;){
        max = Math.max(...priorities);
        if(max > priorities[0]){
            priorities.push(priorities[0]);
            index.push(index[0]);
            priorities.shift();
            index.shift();
        }
        else{
            result.push({priority : priorities[0], idx : index[0]});
            priorities.shift();
            index.shift();
        }
        
        
    }
    for(let i=0;i<result.length;i++)
        {
            if(result[i].idx === location)
                {
                    return i+1;
                }
        }
}

코드 내용 설명

중요도가 높지않다면 index와 해당 값을 담을 수 있는 result와 index를 처리할 수 있는 index가 존재한다.

priorities.map((x,i)=>index.push(i));

해당 index에 값을 넣는다. ex) [0,1,2,3,4]...

 for(;priorities.length != 0 ;){
        max = Math.max(...priorities);
        if(max > priorities[0]){
            priorities.push(priorities[0]);
            index.push(index[0]);
            priorities.shift();
            index.shift();
        }
        else{
            result.push({priority : priorities[0], idx : index[0]});
            priorities.shift();
            index.shift();
        }
        
        
    }

해당 최대값보다 값이 작으면 뒤로보내주고 이를 index의 값에도 같이 적용시킨다.

해당 최대값보다 작지 않으면 그때는 인쇄를 해야하므로 result 부분에 해당 값과 index값을 넣어준다.

    for(let i=0;i<result.length;i++)
        {
            if(result[i].idx === location)
                {
                    return i+1;
                }
        }

진행을 하면서 return은 몇번째로 인쇄되는지인데 0번째로 인쇄되는 것이 아닌 1번째부터 인쇄를 시작하기 때문에 해당 값을 찾은 순간의 i가 아닌 1개 더 많은 i+1를 리턴한다.


1차 수정한 코드


function solution(priorities, location) {
    let max = Math.max(...priorities);
    let result=[];
    let index = [];
    
    priorities.map((x,i)=>index.push(i));
    
    while(priorities.length !==0){

        if(max > priorities[0]){
            priorities.push(priorities[0]);
            index.push(index[0]);
            priorities.shift();
            index.shift();
        }
        else{
            result.push({priority : priorities[0], idx : index[0]});
            priorities.shift();
            index.shift();
            max = Math.max(...priorities);
        }
    }
    
    for(let i=0;i<result.length;i++)
            if(result[i].idx === location)
                    return i+1;
}

필요없는 num제거
for문 괄호 단축
max = Math.max(...priorities);는 else문이 끝날때만 바뀌므로 else문 안에 넣어 반복을 줄인다.
for문을 while문으로 변경


2차 수정한 코드


function solution(priorities, location) {
    let max = Math.max(...priorities);
    const result=[];
    const index = [];
    
    priorities.map((x,i)=>index.push(i));
    
    while(priorities.length >0){

        if(max > priorities[0]){
            priorities.push(priorities[0]);
            index.push(index[0]);
            priorities.shift();
            index.shift();
        }
        else{
            result.push({priority : priorities[0], idx : index[0]});
            priorities.shift();
            index.shift();
            max = Math.max(...priorities);
        }
    }
    
    for(let i=0;i<result.length;i++)
            if(result[i].idx === location)
                    return i+1;
}

let 필요없는 부분을 const로 변경
priorities.length가 0보다 클때반복이 좀더 가독성 높고 !==보단 >가 처리속도가 빠를듯 하다.

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글