안녕하세요

프로그래머스 JS [택배상자] 본문

프로그래머스/Lv.2

프로그래머스 JS [택배상자]

sakuraop 2023. 1. 16. 02:35

택배상자

문제와 풀이
 

1) 메인벨트, 보조벨트 가 있다.

main = [5,4,3,2,1]
support = []
 
 

2) 벨트는 일렬로 되어 있고 상자는 입구의 하나만 꺼낼 수 있다.

=> pop()만 가능
 
 
      sideBelt.push(mainBelt.pop());
 
 

3) 상자는 바닥에 놓으면 안된다.

 
 

4) 메인벨트에서 보조벨트로 상자를 옮길 수 있다.

main => support
main = [5,4,3,2]
support = [1]
 
 
    // 메인벨트에 상자가 남아 있지만, 목표대상이 없으면 [메인벨트 => 보조벨트]
    if (mainBelt.at(-1) && sideBelt.at(-1) !== order[index] && mainBelt.at(-1) !== order[index]) {
      sideBelt.push(mainBelt.pop());
      continue;
    }
 
 

5) 순서에 맞게 트럭에 상자를 실어라.

order = [4, 3, 1, 2, 5]
 
main => support
main = [5,4]
support = [1,2,3]
truck = []
 
main => truck
main = [5]
support = [1,2,3] 
truck = [4]
 
support => truck
main = [5]
support = [1,2] 
truck = [4,3]
 
 
    // 목표대상이 메인벨트에 있으면 [메인벨트 => 트럭]
    if (mainBelt.at(-1) && mainBelt.at(-1) === order[index]) {
      truck.push(mainBelt.pop());
      index++;
      continue;
    }
    // 목표대상이 보조벨트에 있으면 [보조벨트 => 트럭]
    if (sideBelt.at(-1) && sideBelt.at(-1) === order[index]) {
      truck.push(sideBelt.pop());
      index++;
      continue;
    }
 
 

6) 이제 truck에 1을 실어야 하는데, 못 싣는다.

main은 5가 입구를 막고, main = [5]
support는 2가 입구를 막고 있어서, support = [1,2
support 안에 있는 1을 꺼낼 수 없으므로 종료시킨다.
 
 
    // 보조 벨트 안에 목표대상이 들어 있으면 꺼낼 수 없으므로 break
    if ((sideBelt.indexOf(order[index]) !== -1 && sideBelt.at(-1) !== order[index]) || truck.length === order.length) {
      break;
    }
 

7) 트럭에 실려있는 상자의 개수를 반환한다.

  return truck.length;
 
 
 
제한사항
  • 1 ≤ order의 길이 ≤ 1,000,000
  • order는 1이상 order의 길이 이하의 모든 정수가 한번씩 등장합니다.
  • order[i]는 기존의 컨테이너 벨트에 order[i]번째 상자를 i+1번째로 트럭에 실어야 함을 의미합니다.

입출력 예orderresult
[4, 3, 1, 2, 5] 2
[5, 4, 3, 2, 1] 5
 

 
function solution(order) {
  const mainBelt = new Array((length = order.length)).fill().map((_, index) => index + 1).reverse();
  const sideBelt = [];
  const truck = [];
  let index = 0;

  while (true) {
    // 메인벨트에 상자가 남아 있지만, 목표대상이 없으면 [메인벨트 => 보조벨트]
    if (mainBelt.at(-1) && sideBelt.at(-1) !== order[index] && mainBelt.at(-1) !== order[index]) {
      sideBelt.push(mainBelt.pop());
      continue;
    }
    // 목표대상이 메인벨트에 있으면 [메인벨트 => 트럭]
    if (mainBelt.at(-1) && mainBelt.at(-1) === order[index]) {
      truck.push(mainBelt.pop());
      index++;
      continue;
    }
    // 목표대상이 보조벨트에 있으면 [보조벨트 => 트럭]
    if (sideBelt.at(-1) && sideBelt.at(-1) === order[index]) {
      truck.push(sideBelt.pop());
      index++;
      continue;
    }
    // 보조 벨트 안에 목표대상이 들어 있으면 꺼낼 수 없으므로 break
    if ((sideBelt.indexOf(order[index]) !== -1 && sideBelt.at(-1) !== order[index]) || truck.length === order.length) {
      break;
    }
  }
  // 트럭에 있는 상자의 개수 반환
  return truck.length;
}

solution([4, 3, 1, 2, 5]);