[프로그래머스] 프로세스

minkyung·2023년 11월 8일
0
post-thumbnail

내 답안
(엄청 어렵게 품 ...)

function solution(priorities, location) {
  let answer = 0;
  // 1. 인덱스와 중요도 들어있는 Map? 만들기
  const map = new Map(priorities.map((v, i) => [i, v]));
  // 2. map의 key 중에 location 값을 가지고 있지 않을 때 까지 반복
  do {
    // 2-1. map의 value들 끼리만 비교해서 최댓값 구하기
    const maxArray = [...map.values()].sort();
    const max = maxArray[maxArray.length - 1]
    const iterator = map.entries();
    const firstIndex = iterator.next().value;
    const firstIndexKey = firstIndex[0]
    const firstIndexValue = firstIndex[1];
    // 2-2. map의 첫번째 value가 위의 최댓값과 같다면? POP
      if (firstIndexValue === max) {
        map.delete(firstIndexKey)
        answer++;
      } else {
        // 2-3. map.next().value()가 최댓값보다 작다면? PUSH
        map.delete(firstIndexKey)
        map.set(firstIndexKey, firstIndexValue)
      }
  } while (map.has(location))
  return answer;
}

(내가 생각하는) 모범답안

function solution(priorities, location) {
    var arr = priorities.map((priority, index) => {
        return {
            index: index, priority: priority
        };
    });

    var queue = [];

    while(arr.length > 0) {
        var firstEle = arr.shift();
        var hasHighPriority = arr.some(ele => ele.priority > firstEle.priority);
        if (hasHighPriority) {
            arr.push(firstEle);
        } else {
            queue.push(firstEle);
        }
    }

    return queue.findIndex(queueEle => queueEle.index === location) + 1;
}
profile
프론트엔드 개발자

0개의 댓글