ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์˜คํ”ˆ์ฑ„ํŒ…๋ฐฉ(Swift)

2022. 10. 17. 23:55ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์˜คํ”ˆ์ฑ„ํŒ…๋ฐฉ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 

 ๋‚˜์˜ ํ’€์ด

 

๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์ด์šฉํ•˜์—ฌ id์™€ ์—ฐ๊ฒฐ๋œ ๋‹‰๋„ค์ž„์„ ์ง€์ •ํ•˜๊ณ  ํ•œ๋ฒˆ๋” ๋Œ์•„์„œ ํ’€๋ฉด ๋˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

์ด ํ’€์ด์™€ ๋น„์Šทํ•œ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ๋ณด๋‹ˆ ์ฒซ ๋ฒˆ์งธ for๋ฌธ์—์„œ Enter์™€ Change์ธ์ง€ ํ™•์ธํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ user์˜ count๋กœ ๊ฐ’์„ ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค.

 

import Foundation

func solution(_ record:[String]) -> [String] {
    var dic:[String: String] = [:]
    var answer:[String] = []
    for x in record {
        let user = x.components(separatedBy: " ")
        if user[0] == "Enter" || user[0] == "Change" {
            let id = user[1], nickName = user[2]
            dic[id] = nickName
        }
    }
    
    for x in record {
        let user = x.components(separatedBy: " ")
        if user[0] == "Enter" {
            answer.append("\(dic[user[1]]!)๋‹˜์ด ๋“ค์–ด์™”์Šต๋‹ˆ๋‹ค.")
        } else if user[0] == "Leave" {
            answer.append("\(dic[user[1]]!)๋‹˜์ด ๋‚˜๊ฐ”์Šต๋‹ˆ๋‹ค.")
        }
    }
    
    
    return answer
}

 

 

 ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

 

๋ฌธ์ž์—ด์—์„œ contains๋ฅผ ํ†ตํ•ด Change๋ฅผ ๋ถ„๋ฆฌ์‹œํ‚จ๋‹ค๋Š” ์ ๊ณผ ๋ฐฐ์—ด์„ mappingํ•  ๋•Œ actions๋ฐฐ์—ด์ฒ˜๋Ÿผ Enter์™€ Leave๋ฅผ ํ‚ค ๊ฐ’์œผ๋กœ ๋‘” ๊ฒƒ์ด ์‹ ๊ธฐํ•œ ํ’€์ด์˜€๋‹ค.

 

import Foundation

func solution(_ record:[String]) -> [String] {
    let actions: [String: String] = ["Enter":"๋‹˜์ด ๋“ค์–ด์™”์Šต๋‹ˆ๋‹ค.", "Leave":"๋‹˜์ด ๋‚˜๊ฐ”์Šต๋‹ˆ๋‹ค."]
    var dic:[String: String] = [:]
    record.forEach { x in
        let user = x.components(separatedBy: " ")
        if user.count > 2 {
            dic[user[1]] = user[2]
        }
    }
    
    return record.filter{ !$0.contains("Change") }.map { x in
        let user = x.components(separatedBy: " ")
        let newString = dic[user[1]]! + actions[user[0]]!
        return newString
    }
}