[백준/Node.js] 컨베이어 벨트 위의 로봇 #20055

welchs·2021년 8월 8일
0

백준

목록 보기
8/10

짧은 썰

4일전에 처음 풀어봤는데 못 풀어서 풀이봤었고, 오늘 다시 푼 문제
푼 시간은 23분정도 걸렸고, 문제 아이디어는 알고 있었기 때문에 다시 풀 때는 그렇게 어렵지 않았다.
그리고 조건을 함수 단위로 나눠어서 큰 틀을 가지고 문제를 푸니까 확실히 실수도 덜 하는듯하다.
solution함수 안에 코드가 짧아져서 가독성이 올라가는 것도 좋은 것 같다.
이런식으로 계속 풀어보자

코드

const fs = require('fs');

const getZeroCount = (arr) =>
  arr.reduce((acc, cur) => (cur === 0 ? acc + 1 : acc), 0);

const rotate = (arr, robots) => {
  const last = arr.pop();
  arr.unshift(last);

  robots.pop();
  robots.unshift(false);
};

const moveRobots = (arr, robots, N) => {
  for (let i = N - 2; i > -1; i--) {
    if (!robots[i]) continue;

    if (!robots[i + 1] && arr[i + 1] > 0) {
      robots[i + 1] = true;
      robots[i] = false;
      arr[i + 1] -= 1;
    }
  }
};

const addRobot = (arr, robots) => {
  if (arr[0] > 0) {
    arr[0] -= 1;
    robots[0] = true;
  }
};

const removeNthRobot = (robots, n) => {
  robots[n] = false;
};

const solution = (N, K, arr) => {
  const robots = new Array(N).fill(false);
  let stage = 0;

  while (getZeroCount(arr) < K) {
    stage++;
    rotate(arr, robots);
    if (robots[N - 1]) removeNthRobot(robots, N - 1);

    moveRobots(arr, robots, N);
    if (robots[N - 1]) removeNthRobot(robots, N - 1);

    addRobot(arr, robots);
  }

  return stage;
};

const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const [N, K] = input[0].split(' ').map(Number);
const arr = input[1].split(' ').map(Number);

console.log(solution(N, K, arr));
profile
고수가 되고 싶은 조빱

0개의 댓글