https://www.acmicpc.net/problem/25593
const filePath = process.platform === 'linux' ? 0 : './input.txt';
const [N, ...lines] = require('fs').readFileSync(filePath).toString().split('\n');
const dict = {};
for (let i = 0; i < Number(N); i++) {
const startIndex = i * 4;
const week = lines.slice(startIndex, startIndex + 4);
week[0].split(' ').forEach(name => {
if (name !== '-') {
dict[name] = dict[name] ? dict[name] + 4 : 4;
}
});
week[1].split(' ').forEach(name => {
if (name !== '-') {
dict[name] = dict[name] ? dict[name] + 6 : 6;
}
});
week[2].split(' ').forEach(name => {
if (name !== '-') {
dict[name] = dict[name] ? dict[name] + 4 : 4;
}
});
week[3].split(' ').forEach(name => {
if (name !== '-') {
dict[name] = dict[name] ? dict[name] + 10 : 10;
}
});
}
const hours = Object.values(dict);
if (hours.length === 0 || Math.max(...hours) - Math.min(...hours) <= 12) {
console.log('Yes');
} else {
console.log('No');
}
시간 슬롯과 기간을 하드코딩하지 않기
시간 슬롯을 동적으로 반복 처리: 이를 통해 반복적인 코드를 줄일 수 있습니다.
빈 줄과 입력 다듬기 처리: 입력 줄에서 불필요한 공백을 제거해 주는 것이 좋습니다. 앞뒤 공백을 다듬고 빈 줄을 처리하여 런타임 오류를 방지할 수 있습니다.
의미 있는 변수 이름 사용: 더 의미 있는 변수 이름을 사용하면 코드의 가독성이 향상됩니다.
잘못된 입력 검사 추가: 입력 유효성 검사를 추가하면 코드의 견고성이 향상됩니다.
const fs = require('fs');
const filePath = process.platform === 'linux' ? 0 : './input.txt';
const [N, ...lines] = fs.readFileSync(filePath).toString().trim().split('\n');
const timeSlots = [
{ duration: 4, index: 0 }, // 08:00~12:00
{ duration: 6, index: 1 }, // 12:00~18:00
{ duration: 4, index: 2 }, // 18:00~22:00
{ duration: 10, index: 3 }, // 22:00~08:00
];
const workerHours = {};
for (let i = 0; i < Number(N); i++) {
const startIndex = i * 4;
const weekLines = lines.slice(startIndex, startIndex + 4);
timeSlots.forEach(slot => {
const line = weekLines[slot.index].trim();
const names = line.split(' ');
names.forEach(name => {
if (name !== '-') {
workerHours[name] = (workerHours[name] || 0) + slot.duration;
}
});
});
}
const hoursArray = Object.values(workerHours);
if (hoursArray.length === 0 || Math.max(...hoursArray) - Math.min(...hoursArray) <= 12) {
console.log('Yes');
} else {
console.log('No');
}
오늘 배운 점 (TIL)
오늘은 자바스크립트 코드 개선을 통해 하드코딩을 피하고 데이터 구조를 활용하여 확장성을 높이는 방법을 배웠습니다. 시간 슬롯과 같은 관련 데이터를 배열에 저장함으로써 동적으로 반복할 수 있어 코드 유지보수가 더 쉬워집니다. 입력을 다듬고 의미 있는 변수명을 사용함으로써 코드의 견고성과 가독성이 향상됩니다. 또한, 논리적 OR(||
)을 이용하여 객체 내 누적 로직을 간결하게 작성할 수 있었습니다.