[백준] 14891 톱니바퀴- javascript

Yongwoo Cho·2022년 4월 22일
0

알고리즘

목록 보기
80/104
post-thumbnail

📌 문제

https://www.acmicpc.net/problem/14891

📌 풀이

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : 'input.txt';
let input = fs.readFileSync(filePath).toString().trim().split('\n');

const wheelInfo = Array.from({ length: 4 }, (_, i) => input[i].split(''));
const rotations = Array.from({ length: +input[4] }, (_, i) => input[i + 5].split(' ').map(Number));
const check = Array.from({ length: 4 }, () => false);

function rotateWheel(wheelNum, direction) {
  if (direction === 1) {
    let tmp = wheelInfo[wheelNum][7];
    wheelInfo[wheelNum].pop();
    wheelInfo[wheelNum] = [tmp, ...wheelInfo[wheelNum]];
  } else {
    let tmp = wheelInfo[wheelNum][0];
    wheelInfo[wheelNum].shift();
    wheelInfo[wheelNum] = [...wheelInfo[wheelNum], tmp];
  }
}

function setRotation(wheelNum, direction) {
  check[wheelNum] = true;
  const [prevWheelNum, nextWheelNum] = [wheelNum - 1, wheelNum + 1];

  if (prevWheelNum >= 0 && !check[prevWheelNum]) {
    if (wheelInfo[prevWheelNum][2] !== wheelInfo[wheelNum][6]) {
      setRotation(prevWheelNum, direction * -1);
    }
  }

  if (nextWheelNum < 4 && !check[nextWheelNum]) {
    if (wheelInfo[nextWheelNum][6] !== wheelInfo[wheelNum][2]) {
      setRotation(nextWheelNum, direction * -1);
    }
  }

  rotateWheel(wheelNum, direction);
}

for (const [wheelNum, dir] of rotations) {
  check.fill(false);

  setRotation(wheelNum - 1, dir);
}

let ans = 0;
let plus = 1;

for (const [wheelFirstInfo] of wheelInfo) {
  if (wheelFirstInfo) ans += plus;

  plus *= 2;
}

console.log(ans);

✔ 알고리즘 : 구현

✔ 재귀를 사용하여 시작점 톱니바퀴의 전, 후 톱니바퀴를 회전시켜야 하는 문제

✔ 전, 후 톱니바퀴 확인

if (prevWheelNum >= 0 && !check[prevWheelNum]) {
    if (wheelInfo[prevWheelNum][2] !== wheelInfo[wheelNum][6]) {
      setRotation(prevWheelNum, direction * -1);
    }
  }

  if (nextWheelNum < 4 && !check[nextWheelNum]) {
    if (wheelInfo[nextWheelNum][6] !== wheelInfo[wheelNum][2]) {
      setRotation(nextWheelNum, direction * -1);
    }
  }

❗ 톱니바퀴끼리 넘어갈때는 direction이 항상 바뀐다.

✔ 회전시키는 함수

function rotateWheel(wheelNum, direction) {
  if (direction === 1) {
    let tmp = wheelInfo[wheelNum][7];
    wheelInfo[wheelNum].pop();
    wheelInfo[wheelNum] = [tmp, ...wheelInfo[wheelNum]];
  } else {
    let tmp = wheelInfo[wheelNum][0];
    wheelInfo[wheelNum].shift();
    wheelInfo[wheelNum] = [...wheelInfo[wheelNum], tmp];
  }
}

시계 방향(direction = 1) 👉 맨 뒤 원소를 맨 앞으로
반시계 방향(direction = -1) 👉 맨 앞 원소를 맨 뒤로

✔ 점수 계산

for (const [wheelFirstInfo] of wheelInfo) {
  if (wheelFirstInfo) ans += plus;

  plus *= 2;
}

✔ 난이도 : 백준 기준 골드 5

profile
Frontend 개발자입니다 😎

0개의 댓글