몸과 마음이 건전한 SW 개발자

프로그래머스 [Lv. 2] [3차] 방금그곡 {언어 : JavaScript} 본문

카테고리 없음

프로그래머스 [Lv. 2] [3차] 방금그곡 {언어 : JavaScript}

스위태니 2024. 5. 10. 16:52

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/17683

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

정답 코드

function solution(m, musicinfos) {
    let answer = '(None)';
    let maxTimes = 0;
    
    const musicDevide = (music) => {
        const stack = [];
        const lenMusic = music.length;
        let jdx = 0;
        while (jdx < lenMusic) {
            const cv = music[jdx];
            if (jdx+1 <= lenMusic && music[jdx+1] == "#") {
                jdx += 1;
                stack.push(cv+"#");
            } else {
                stack.push(cv);
            };
            jdx += 1;
        };
        return stack;
    };
    
    const calTimes = (st, et) => {
        const stTmp = st.split(":");
        const etTmp = et.split(":");
        const stTimes = parseInt(stTmp[0]) * 60 + parseInt(stTmp[1]);
        const etTimes = parseInt(etTmp[0]) * 60 + parseInt(etTmp[1]);
        return etTimes - stTimes;
    };
    
    const newM = musicDevide(m);
    const lenM = newM.length;
    
    for (const music of musicinfos) {
        const [st, et, title, rhythm] = music.split(",");
        const times = calTimes(st, et);
        const newRhythm = musicDevide(rhythm);
        const lenR = newRhythm.length;
        let isValid = 0;
        let [idx, checkIdx] = [0, 0];
        while (idx < times) {
            if (newRhythm[idx%lenR] == newM[checkIdx%lenM]) {
                checkIdx += 1;
                if (checkIdx && checkIdx % lenM == 0) {
                    isValid += 1;
                };
            } else {
                checkIdx = 0;
                if (newRhythm[idx%lenR] == newM[0]) {
                    checkIdx += 1;
                };
            };
            idx += 1;
        };
        if (isValid && times > maxTimes) {
            answer = title;
            maxTimes = times;
        };
    };
    return answer;
}

풀이 방법

  1. 리듬에 #이 있기 때문에 stack에 하나하나 확인해서 분류해준다.
  2. 끝나는 시각에서 시작하는 시각을 빼서 시간을 구한다.
  3. 시간 만큼 jdx를 증가시키면서 m과 일치하는지 확인한다.
  4. 일치하는 경우 시간이 긴 쪽을 answer에 저장한다.

느낀점

  • #이 있다는 점을 망각하고 풀어서 틀렸었다.
  • 다시 찾기는 했지만 문제를 꼼꼼하게 읽는 것이 항상 중요하다.