Lv.2 프린터

·2022년 4월 5일

프로그래머스

목록 보기
5/18
post-thumbnail

문제 설명

자료 구조

  • count
    • 타입 : 정수
    • 저장 데이터 : 출력되는 순서
  • head
    • 타입 : 배열
    • 저장 데이터 : 해당 문서의 숫자와 처음 위치(location)

풀이 과정

하라는 대로만 구현하는 문제다.

  • 더 큰 수가 있으면 맨 뒤로 넘긴다.
  • 더 큰 수가 없으면 출력한다.
  • location에 있던 문서가 몇 번째에 출력되는지 알아낸다.

당연히 파이썬 deque같은 걸 쓰면 더 편하다.

  1. 배열 재정리.
    [1,1,9,1,1,1] =>
    [[1,0], [1,1], [9,2], [1,3], [1,4], [1,5]]
    로 인덱스값을 부여해서 배열을 다시 만들었다.
    예제에선 location = 0이므로 [1,0]이 언제 출력되는지 알아내보자.

  2. 1보다 큰 값이 있으므로 맨 뒤로 넘긴다.

  3. 9를 출력하고 count를 1 증가한다. (첫 번째 문서가 출력됐으니까)

  4. [1,3], [1,4], [1,5], [1,0], [1,1]이 남았다.
    [1,0]이 나올 때까지 계속 출력하며 count를 증가시킨다.

  5. location이 일치하는 숫자가 나오면 해당 count를 return하고 종료.

코드 구현(JavaScript)

function solution(priorities, location) {
  let count = 1;
  priorities = priorities.map((_, i) => [_, i]);

  while (priorities.length > 0) {
    let head = priorities[0];
    if (priorities.some((arr) => arr[0] > head[0])) {
      priorities.splice(0, 1);
      priorities.push(head);
    } else {
      if (head[1] === location) {
        return count;
      }
      priorities.splice(0, 1);
      count++;
    }
  }
}

출처: 프로그래머스

profile
모르는 것 투성이

0개의 댓글