
const fs = require('fs');
const path = process.platform === 'linux' ? '/dev/stdin' : 'input.txt';
const inputs = fs
.readFileSync(path)
.toString()
.trim()
.split('\n')
.map((it) => it.split(' ').map(Number));
const [n, m] = inputs.splice(0, 1).flat();
let floors = inputs.map(([l, d]) => {
if (d === 0) return [1, l, d];
return [m - l + 1, m, d];
});
// 올라갈 수 있는지 알려주는 애
const canGoUp = (currentFloor) => {
const [s, e, d] = floors[currentFloor];
const [nS, nE, nD] = floors[currentFloor + 1];
if (s - 1 === nE || nS - 1 === e) return true;
if (nE >= s && nS <= e) return true;
return false;
};
// 움직여 주는애
const moveStick = () => {
floors = floors.map(([s, e, d]) => {
if (d === 0) {
if (e === m) [s - 1, e - 1, 1];
else return [s + 1, e + 1, d];
}
if (s === 1) return [s + 1, e + 1, 0];
else return [s - 1, e - 1, d];
});
};
let current = 0;
let time = 0;
while (current < n - 1) {
if (canGoUp(current)) {
current += 1;
continue;
}
// 움직일 수 없다면
moveStick();
time += 1;
}
console.log(time);
⏰ 소요한 시간 : -
n과 m을 분리시켜준 뒤, 그 다음줄 부터 floors 배열에 각 층의 막대기 정보(시작인덱스, 끝인덱스, 진행방향)를 저장해주었다.
그 후 현재 층을 알려주는 변수 current, 현재까지 몇 시간이 걸렸는지 알려주는 변수 time을 만들어 준 뒤, while문을 돌면서 올라갈 수 있는지 없는지 확인해준다.
만약 현재층에서 올라갈 수 있다면, current변수를 1 증가시켜주고 다음 반복을 수행하고, 올라갈 수 없다면 막대기를 움직여주고 시간을 1 증가시켜주면 된다.
이 때 올라갈 수 있는지 확인해주는 canGoUp함수는 현재 위치의 시작 값 끝 값이랑 끝 위치의 시작 값 끝 값을 받아와 범위를 체크해주면 된다.
움직여주는 함수는 모든 층을 돌면서 배열 내부의 값을 방향에 따라 움직여 주면 된다.