오 문제 보자마자 어캐풀어야할지 감잡기가 어려웠다.
그래도 차근차근 나눠서 함수 단위로 생각하니까 풀렸다. (나이스!)
여기선 전체 4개의 톱니바퀴를 한 번에 어떻게 회전할지를 계산하는게 관건이다.
포기하고 다른 사람풀이 보려다가 마음잡고 푸니 풀려서 기분이 좋다.
const fs = require('fs');
const changeStatus = (rotateDirection, gears, idx, status, check) => {
check[idx] = true;
status[idx] = rotateDirection;
if (idx - 1 >= 1) {
if (!check[idx - 1] && gears[idx][6] !== gears[idx - 1][2]) {
changeStatus(-rotateDirection, gears, idx - 1, status, check);
}
}
if (idx + 1 <= 4) {
if (!check[idx + 1] && gears[idx][2] !== gears[idx + 1][6]) {
changeStatus(-rotateDirection, gears, idx + 1, status, check);
}
}
};
const rotate = (gears, gearIdx, rotateDirection) => {
const check = new Array(5).fill(false);
const status = new Array(5).fill(0);
changeStatus(rotateDirection, gears, gearIdx, status, check);
for (let i = 1; i <= 4; i++) {
if (status[i] === 0) continue;
else if (status[i] === 1) {
const last = gears[i].pop();
gears[i].unshift(last);
} else {
const first = gears[i].shift();
gears[i].push(first);
}
}
};
const calcScore = (gears) => {
let score = 0;
for (let i = 1; i <= 4; i++) {
score += gears[i][0] === '1' ? 2 ** (i - 1) : 0;
}
return score;
};
const solution = (gears, commands) => {
gears.unshift(null);
commands.forEach(([gearIdx, rotateDirection]) => {
rotate(gears, gearIdx, rotateDirection);
});
return calcScore(gears);
};
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const gears = input.slice(0, 4).map((v) => [...v]);
const commands = input.slice(5).map((v) => v.split(' ').map(Number));
console.log(solution(gears, commands));