Level
프로그래머스 Lv3
Day
18일
kakao
2018 카카오 블라인드
 
function solution(n, t, m, timetable) {
    var answer = '';

    const toMinute = hhmm => {
        const [hh, mm] = hhmm.split(':')
        return 60 * hh + +mm 
    }

    const minuteToHHMM = minute => {
        const hh = Math.floor(minute / 60)
        const mm = minute - hh * 60;
        return (hh< 10 ? '0' + hh : hh) + ':' + (mm < 10 ? '0' + mm : mm);
    }

    timetable = timetable.map(hhmm => toMinute(hhmm)).sort((a,b) => a - b)
    const bustable = Array(n).fill(0).map((bus, i) => ({arrivedAt : 540 + i*t, crews:[]}))
    const rideToBus = (busIndex, crewAt) => {
        if(busIndex === bustable.length) return -1;

        const bus = bustable[busIndex]
        const nextBusIndex = busIndex + 1;

        if(bus.crews.length >= m) return rideToBus(nextBusIndex, crewAt)

        if(bus.arrivedAt >= crewAt){
            bus.crews.push(crewAt)
            return busIndex;
        }

        return rideToBus(nextBusIndex, crewAt);
    }

    let current = 0;
    for(let crewAt of timetable){
        const ridedBus = rideToBus(current, crewAt)

        if(ridedBus===-1) break; 

        current = ridedBus
    }

    const lastBus = bustable[bustable.length-1]

    if(lastBus.crews.length <m) return minuteToHHMM(lastBus.arrivedAt);
    const lastCrew = lastBus.crews.pop(); 

    return minuteToHHMM(lastCrew -1);

}