알고리즘/프로그래머스 - JS

[프로그래머스 - JS] level.2 프로세스 👍

개발자성장기 2023. 5. 20. 19:54
반응형

 


나의 풀이 

queue로 풀지만 index가 필요하기에 배열을 이중배열로 만들어서 풀어야겠다 싶었다. 

위 예제로 보자면 

priorities = [ [2,0] , [1, 1], [3, 2], [2, 3] ]   이런식으로  [[priority, index], ....] 이렇게 구성이 된다. 

이것을 기준으로 더 높은 우선순위가 없다면  queue에 들어간다 즉 처리된다는 뜻이다. 

 

그런데 이때 index === location 이면  바로 결과값을 return 한다. 

더 높은 우선순위가 있다면 다시 priorities 배열에 넣어준다. 

 

function solution(priorities, location) {
    const queue = []
    priorities = priorities.map((priority, index) => [priority, index])
    
    while(priorities.length) {
        const [priority, index] = priorities.shift()
        const higherImportance = priorities.findIndex(([value, _]) => value > priority)
        
        if(higherImportance === -1){
            if(index === location) return queue.length + 1  
            queue.push([priority, index])  
            continue
        }
        
        priorities.push([priority, index])
    }
}

 

 

다른사람 풀이를 보면서 생각해보니 굳이 queue를 만들필요가 없어보였다 let count = 0 해서  처리될때마다 +1 해주면 될 것 같다. 

 


다른 사람 풀이 

 

풀이 너무 좋음

function findPrintOrder(priorities, location) {
  let count = 0; // 처리된 프로세스 수
  let maxPriority = Math.max(...priorities); // 최대 우선순위

  while (true) {
    const currentProcess = priorities.shift(); // 대기중인 프로세스를 큐에서 꺼냄

    if (currentProcess === maxPriority) {
      count++; // 프로세스 실행
      if (location === 0) return count; // 찾고자 하는 프로세스일 경우 결과 반환
      maxPriority = Math.max(...priorities); // 최대 우선순위 갱신
    } else {
      priorities.push(currentProcess); // 큐에 다시 넣음
    }

    location = location === 0 ? priorities.length - 1 : location - 1; // 위치 조정
  }
}

 

이건 생각지 못했다. 

맨 마지막에 보면  location을 재조정해준다. 

즉 shift로 앞에서 빼오기에 location이 앞으로 한칸씩 이동되어진다. 

그래서 location 이 0이면 맨뒤로 location이 수정되고 0이아니라면 앞으로 한칸 이동한다. 

그렇게 처리가 되다가 우선순위가 제일 높은 프로세스가 실행되었을 때 location이 0이면 결과를 찾은 것이다. 

 

즉 이 풀이는 최대 우선순위를 계속 갱신하면서 location을 0으로 만드는 풀이다.   

다시말해 처음 location이 0이 되는 순간이 바로 우선순위를 기다리다가 드디어 실행되는 process이다. 

 

와 진짜 좋은 생각인 것 같다.  

 

이렇게하면 내 코드보다 훨씬 처리 속도도 빠르고  코드도 간결해서 가독성이 좋다. 

 

반응형