(백준) 전주 듣고 노래 맞히기 성공

hwisaac·2024년 11월 3일
0

코테TIL

목록 보기
7/20

문제 링크

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

풀이

const filePath = process.platform === "linux" ? 0 : "./input.txt";
let input = require("fs").readFileSync(filePath).toString().trim().split("\n");
const [N, M] = input[0].split(' ').map(Number); // 정확히 음을 아는 노래 갯수 N, 맞히기를 시도할 노래의 갯수 M
const given = input.slice(1, N+1)
const problem = input.slice(N+1, N+M+1)

const dict ={}
for (let i = 0; i < given.length; i++) {
    let subInput = given[i].split(' ')
    const l = Number(subInput[0]);
    const title = subInput[1];
    const codes = subInput.slice(2).join('').slice(0,3)
    if (Object.hasOwn(dict, codes)) {
        dict[codes] = '?'
    }else{
        dict[codes] = title
    }
}
let result = ''
for (let i=0 ; i < problem.length; i++){
    const line = problem[i].replaceAll(' ', "")
    if (!dict[line]){
        result += '!\n'
    }else{
        result += dict[line] + '\n'
    }
}
console.log(result)

코드 리뷰 및 개선점

  1. hasOwnProperty 대신 in 연산자 사용
    hasOwnProperty 메서드를 사용하는 대신 in 연산자를 사용하면 코드가 더욱 간결해집니다. in 연산자는 객체의 속성 여부를 검사할 때 짧고 읽기 쉬운 방식입니다.

  2. Array.join('').slice(0, 3) 대신 Array.slice(0, 3).join('') 사용
    코드의 const codes = subInput.slice(2).join('').slice(0, 3) 부분에서 먼저 음이름을 모두 합치고 나서 세 글자만 추출하는 대신, 먼저 필요한 세 음만 슬라이싱하여 결합하는 방법을 사용하면 불필요한 문자열 조작이 줄어들어 약간의 성능 개선을 이끌어낼 수 있습니다.

  3. replaceAll 대신 split-join으로 문자열 결합 최적화
    노래 제목을 추론하는 부분에서 replaceAll 대신 split-join 패턴을 사용할 수 있습니다. 이는 상황에 따라 성능에 유리할 수 있습니다.

  4. 코드 간결화
    const codes 부분을 정리한 후 결과를 바로 result에 누적하여 중간 변수를 최소화하는 방식으로 개선할 수 있습니다.

개선된 코드 예시

const filePath = process.platform === "linux" ? 0 : "./input.txt";
let input = require("fs").readFileSync(filePath).toString().trim().split("\n");
const [N, M] = input[0].split(" ").map(Number);
const given = input.slice(1, N + 1);
const problem = input.slice(N + 1, N + M + 1);

const dict = {};

for (const entry of given) {
  const [l, title, ...notes] = entry.split(" ");
  const codes = notes.slice(0, 3).join("");
  dict[codes] = dict[codes] ? "?" : title;
}

let result = "";
for (const attempt of problem) {
  const line = attempt.split(" ").join("");
  result += dict[line] ? dict[line] + "\n" : "!\n";
}

console.log(result);

개선점 요약 (TIL)

  • 객체의 키 존재 여부 확인: hasOwnProperty 대신 in 연산자 사용으로 코드 가독성과 간결성을 높임.
  • 효율적인 슬라이싱과 문자열 결합: 필요한 음만 슬라이싱 후 결합하여 문자열 조작을 간소화.
  • replaceAll의 대안: replaceAll 대신 split-join 패턴을 활용하여 잠재적 성능 향상.
  • 코드 구조 개선: 반복문 내 중간 변수를 최소화하여 성능 최적화 및 코드 길이 단축.

0개의 댓글