[프로그래머스 lev2/JS] 프린터

woolee의 기록보관소·2022년 10월 31일
0

알고리즘 문제풀이

목록 보기
30/178

문제 출처

프로그래머스 lev2 - 프린터

문제

나의 풀이

모든 애들의 중요도가 다르다면 단순히 sort()로 풀 수 있을 것 같다. 하지만 중요도가 같은 경우가 있을 수 있으므로 일일이 while 문으로 빼주면서 res 변수로 추적해야 한다고 판단했다.

while 문을 순회하면서,
1. shift()로 뺀 애(tg, 이때 res에서도 shift 해서 res를 추적한다)를 나머지 애들과 비교해서 하나라도 뺀 애보다 크면, 다시 뒤로 넣어주고(tg랑 res 모두 넣어줘야 함)
2. 큰 게 없다면 tg는 필요 없고, res.shift()인 ans만 answer 배열에 넣는다.

function solution(priorities, location) {
  let res = Array.from({length:priorities.length}, () => 0);
  for (let i=0; i<res.length; i++) res[i]=i;

  let answer = [];
  while (priorities.length > 0) {
    let tg = priorities.shift();
    let ans = res.shift();

    let jud=true;
    for (let x of priorities) {
      if (tg < x) {
        jud=false;
      }
      if (jud==false) break;
    }
    
    if (jud==false) {
      res.push(ans)
      priorities.push(tg)
    }
    else if (jud==true) answer.push(ans);
  }

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

// console.log(solution([2, 1, 3, 2], 2)); // 1
console.log(solution([1, 1, 9, 1, 1, 1], 0)); // 5

다른 풀이

some() : 배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트 (true / false 반환)

  • 용례
const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// expected output: true
function solution(priorities, location) {
  var list = priorities.map((t,i)=>({
      my : i === location,
      val : t
  }));

  var count = 0;        
  while(true){
      var cur = list.splice(0,1)[0]; /* var cur = list.shift(); 랑 같은 의미 */
      console.log(cur);
      if(list.some(t=> t.val > cur.val )){
          list.push(cur);                        
      }
      else{            
          count++;
          if(cur.my) return count;
      }
  }
}

// console.log(solution([2, 1, 3, 2], 2)); // 1
console.log(solution([1, 1, 9, 1, 1, 1], 0)); // 5
profile
https://medium.com/@wooleejaan

0개의 댓글