๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] Swift 2022 kakao ์ฃผ์ฐจ ์š”๊ธˆ ๊ณ„์‚ฐ

by Jouureee 2022. 4. 19.

๋ฌธ์ œ :
https://programmers.co.kr/learn/courses/30/lessons/92341

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ฃผ์ฐจ ์š”๊ธˆ ๊ณ„์‚ฐ

[180, 5000, 10, 600] ["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"] [14600, 34400, 5000]

programmers.co.kr


๋ถ„์„ :
string ํŒŒ์‹ฑ์„ ์ด์šฉํ•œ ๊ตฌํ˜„ ๋ฌธ์ œ์˜€๋‹ค. C++์—์„œ๋Š” ์‹œ๊ฐ„์„ ๊ตฌํ•˜๋Š”๋ฐ * 60์„ ํ•˜๋Š” ๋“ฑ ๋˜๊ฒŒ ๋ณต์žกํ–ˆ๋Š”๋ฐ swift๋Š” DateFormatter()๊ฐ€ ์žˆ๋‹ค ํžˆํžˆ ๊ทธ๋ž˜์„œ ์ž…์ฐจ, ์ถœ์ฐจ ์‹œ๊ฐ„์„ ์ดˆ๋กœ ๋ฐ”๊พธ์–ด ๋ถ„๋‹จ์œ„๋กœ ๋ˆ„์ ํ•ด์ฃผ์—ˆ๋‹ค.
๊ทธ๋ฆฌ๊ณ  out์„ ํ• ๋•Œ๋งˆ๋‹ค -1์„ ํ•ด์ฃผ์—ˆ๋Š”๋ฐ -1์ด ์•ˆ๋˜์—ˆ๋‹ค๋ฉด out์„ ํ•˜์ง€ ์•Š์€ ๊ฒƒ์œผ๋กœ outํ•˜์ง€ ์•Š์€ ์ฐจ๋“ค์— ๋Œ€ํ•ด์„œ ํ•œ๋ฒˆ ๋” ๊ฐ’์„ ๋ˆ„์ ์‹œํ‚จ๋’ค cal() ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ์ฃผ์ฐจ ์š”๊ธˆ์„ ๊ณ„์‚ฐํ•˜๊ณ  ์ฐจ ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜์˜€๋‹ค.

Swift ์ฝ”๋“œ :

//
//  main.swift
//  SOMA๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป
//
//  Created by JoSoJeong on 2022/04/19.
//

import Foundation

func timeToSecond(_ s: String) -> Double {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm"
    return Double(dateFormatter.date(from: s)!.timeIntervalSince1970)
}

func cal(_ fees: [Int], _ now: Double) -> Int {
    let defaultCost: Int = fees[1]
    let defaultTime: Double = Double(fees[0])
    if now < defaultTime { return defaultCost }
    let div: Double = Double(fees[2])
    let mul: Double = Double(fees[3])
    return defaultCost + Int(ceil((now - defaultTime) / div) * mul)
}
               
func solution(_ fees:[Int], _ records:[String]) -> [Int] {
    var answer = [(String, Int)]() // number : cost
    var stack: [String : Double] = [:] // ์ž…์ฐจ ์ถœ์ฐจ ์‹œ๊ฐ„ ๊ณ„์‚ฐ
    var dic: [String: Double] = [:] // car number - ๋ˆ„์  ์‹œ๊ฐ„

    for i in records {
        let line = i.split(separator: " ").map { String($0) }
        let secondT: Double = timeToSecond(line[0])
        let number = line[1]

        if (stack[number] != 0) && (line[2] == "IN") {
            // ์ฒ˜์Œ ์ž…์ฐจ
            stack[number] = secondT
        }else if line[2] == "OUT" {
            // ์‹œ๊ฐ„ ๊ณ„์‚ฐ
            // stack pop
            let last = stack[number]!
            stack[number] = -1
            // dic์— ๋ˆ„์ 
            dic[number, default: 0] += (secondT - last) / 60  //์ถœ์ฐจ์‹œ๊ฐ„ - ์ž…์ฐจ์‹œ๊ฐ„
        }
    }
    
    for i in stack { //stack์ด ๋น„์ง€ ์•Š์•˜๋‹ค๋ฉด ์ž…์ฐจ๋Š” ํ–ˆ์œผ๋‚˜ ์ถœ์ฐจํ•˜์ง€ ์•Š์€ ๊ฒƒ
        if i.value != -1 { // ์•„์ง ๋น ์ ธ๋‚˜๊ฐ€์ง€ x
            let lastT = timeToSecond("23:59")
            dic[i.key, default: 0] += (lastT - i.value) / 60
        }
    }
    
    for i in dic {
        let cost = cal(fees, i.value)
        answer.append((i.key, cost))
    }
    
    answer.sort { $0.0 < $1.0 }
    return answer.map { $0.1 }
    
}


๊ฒฐ๊ณผ :

๋Œ“๊ธ€