1 분 소요

part42. [PCCP 기출문제] 3번 / 아날로그 시계

js ver 1.0

function solution(h1, m1, s1, h2, m2, s2) {
    const totalSeconds = ((h2 - h1) * 60 + m2 - m1) * 60 + s2 - s1;
    const meetPoints = new Set();

    const hourHandPosition = (h, m, s) => (h * 30 + m / 2 + s / 120) % 360;
    const minuteHandPosition = (_, m, s) => (m * 6 + s / 10) % 360;
    const secondHandPosition = (s) => (s * 6) % 360;

    const findMeetings = (h, m, s, t, handPositionFn) => {
        const compLoc = handPositionFn(h, m, s);
        const sLoc = secondHandPosition(s);

        if (compLoc < sLoc) {
            if (t >= 60 - s) {
                h += Math.floor((m + 1) / 60);
                m = (m + 1) % 60;
                t -= 60 - s;

                findMeetings(h, m, 0, t, handPositionFn);
            }

            return;
        }

        const rawSecond = handPositionFn == minuteHandPosition ? 10 * (compLoc - sLoc) / 59 : 120 * (compLoc - sLoc) / 719;
        const meetSecond = Math.ceil(rawSecond);

        if (t >= meetSecond) {
            h += Math.floor((m + Math.floor((s + meetSecond) / 60)) / 60);
            m = (m + Math.floor((s + meetSecond) / 60)) % 60;

            const rs = (s + rawSecond) % 60;

            s = (s + meetSecond) % 60;
            t -= meetSecond;

            meetPoints.add(`${h}${m}${rs}`);

            if (rs == 0) {
                s += 1;
                t -= 1;
            }

            findMeetings(h, m, s, t, handPositionFn);
        }
    }

    findMeetings(h1, m1, s1, totalSeconds, hourHandPosition);
    findMeetings(h1, m1, s1, totalSeconds, minuteHandPosition);

    return meetPoints.size;
}

실행결과_js ver 1.0


js ver 1.1

function solution(h1, m1, s1, h2, m2, s2) {
    const start = h1 * 3600 + m1 * 60 + s1;
    const end = h2 * 3600 + m2 * 60 + s2;
    
    const getCnt = (t) => {
       const meetMinute = Math.floor(t * 59 / (10 * 360));
       const meetHour = Math.floor(t * 719 / (120 * 360));

       return meetMinute + meetHour - (t >= (12 * 3600) ? 2 : 1);
    }

    const startCnt = (start * 59 % (10 * 360) == 0 || start * 719 % (120 * 360) == 0 ? 1 : 0);
    
    return getCnt(end) - getCnt(start) + startCnt;
}

실행결과_js ver 1.1


업데이트: