본문 바로가기
알고리즘

[Hash] 주차 요금 계산

by limew 2023. 8. 31.

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

 

프로그래머스

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

programmers.co.kr

로직

record를 돌며 차량 마다 총 소비한 시간을 계산한다

분 단위로 계산하기 위해 (시간* 60+분)으로 계산해준다

IN들어갈때는 위에 계산한 시간을 뺴주고

OUT나갈떄는 더해준다

records 순환을 끝내고 시간이 <= 0인 차량은 아직 안 나온 차량이므로 23:59 시간을 더해준다

챠량마다 총 소비한 돈을 정리한다 

기본시간보다 적거나 같으면 기본요금만 내고, 기본시간보다 크면 기본시간 + ((총 시간 - 기본시간) / 단위 ) * 단위당 요금

단위로 안 나눠질땐 올림한다

차량번호 별로 sort한뒤 각 요금을 리턴한다.

 

전체코드

function solution(fees, records) {
    var answer = [];
    const [defaultTime, defaultCost, unit, unitCost] = fees;
    const parkingTime = {};
    
    for (const record of records) {
        const [t, id, type] = record.split(' ');
        const [h, m] = t.split(':');
        const time = Number(h) * 60 + Number(m);
        
        if (!parkingTime[id]) parkingTime[id] = 0;
        // 들어가면-, 나오면 +
        if (type === 'IN') {
            parkingTime[id] -= time;
        } else if (type === 'OUT') {
            parkingTime[id] += time;
        }
    }
    // 0보다 작은 시간 = 아직 출차하지 않은 차는 23:59에 출차한다
    for (const [id, time] of Object.entries(parkingTime)) {
        if (time <= 0) {
            parkingTime[id] += 1439; // 23*60+59
        }
    }
    // 비용계산
    Object.entries(parkingTime).forEach(([id, time]) => {
        let cost = 0;
        if (time < defaultTime) {
            cost = defaultCost;
        } else {
            cost = defaultCost + Math.ceil((time - defaultTime)/unit)*unitCost;
        }
        answer.push([Number(id), cost]);
        
    })
    answer.sort((a, b) => a[0] - b[0]);
    return answer.map(a => a[1]);
}