ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์œ„์žฅ(Swift)

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

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์œ„์žฅ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

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

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

programmers.co.kr

 

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

 

๋‹ค๋ฅธ ์˜ท์„ ์กฐํ•ฉํ•ด์„œ ์ž…๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋Š” ์นดํ…Œ๊ณ ๋ฆฌ๋งˆ๋‹ค ์ด ์นดํ…Œ๊ณ ๋ฆฌ์— ํ•ด๋‹นํ•˜๋Š” ์˜์ƒ์„ ์ž…์ง€ ์•Š๋Š”๋‹ค์˜ ๊ฒฝ์šฐ์™€ ์ด ์นดํ…Œ๊ณ ๋ฆฌ์— ๋ช‡๊ฐœ์˜ ์˜์ƒ์ด ์žˆ๋Š”์ง€๋งŒ ๊ณ ๋ คํ•˜๋ฉด ๋œ๋‹ค.

 

์˜ˆ๋ฅผ๋“ค์–ด ์ƒ์˜์—๋Š” 2๋ฒŒ, ํ•˜์˜์—๋Š” 3๋ฒŒ์ด ์žˆ์„๋•Œ ์ƒ์˜๋ฅผ ์•„์˜ˆ ์•ˆ ์ž…๊ฑฐ๋‚˜ 1๋ฒˆ ํ˜น์€ 2๋ฒˆ์„ ๊ณ ๋ฅด๋Š” ๊ฒฝ์šฐ -> 3, ํ•˜์˜๋ฅผ ์•„์˜ˆ ์•ˆ ์ž…๊ฑฐ๋‚˜ 1๋ฒˆ ํ˜น์€ 2๋ฒˆ ํ˜น์€ 3๋ฒˆ์„ ๊ณ ๋ฅด๋Š” ๊ฒฝ์šฐ -> 4ํ•ด์„œ ์ด 12๊ฐ€์ง€ ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ๋‚˜์˜จ๋‹ค. ์—ฌ๊ธฐ์„œ ํ•œ ๊ฐ€์ง€๋Š” ๊ผญ ์ž…์–ด์•ผํ•˜๋Š” ์กฐ๊ฑด์ด ์žˆ์œผ๋‹ˆ -1๋งŒ ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

import Foundation

func solution(_ clothes:[[String]]) -> Int {
    var dic: [String: Int] = [:]
    
    for cloth in clothes {
        if dic[cloth[1]] == nil {
            dic[cloth[1]] = 1
        } else {
            dic[cloth[1]]! += 1
        }
    }
    var result = 1
    for x in dic {
        result *= (x.1+1) 
    }
    
    return result-1
}

 

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

 

compactMap, Set, reduce๋ฅผ ์ ์ ˆํžˆ ์‚ฌ์šฉํ•œ ํ’€์ด์ด๋‹ค.

 

compactMap์€ ๋ณดํ†ต์€ 2์ฐจ์›๋ฐฐ์—ด์—์„œ ์‚ฌ์šฉํ•˜๋ฉด 2์ฐจ์› ๋ฐฐ์—ด๋กœ ๋ฆฌํ„ด์„ ํ•˜์ง€๋งŒ ์•„๋ž˜ ์ฝ”๋“œ์ฒ˜๋Ÿผ $0.last!๋กœ ํ•œ ๊ฐœ์˜ ์ˆซ์ž๋งŒ ๋ฆฌํ„ดํ•˜๊ฒŒ ๋œ๋‹ค๋ฉด 1์ฐจ์› ๋ฐฐ์—ด๋กœ ๋ฆฌํ„ดํ•˜๊ฒŒ ๋œ๋‹ค. (์™œ์ธ์ง€๋Š” ๋ชจ๋ฅด๊ฒ ์Šต๋‹ˆ๋‹ค. ํ˜น์‹œ ์•Œ๊ณ  ๊ณ„์‹œ๋ฉด ๋Œ“๊ธ€ ๋ถ€ํƒ๋“œ๋ ค์š”!) 

 

๊ทธ๋ฆฌ๊ณ  ๊ณ ์ฐจํ•จ์ˆ˜๋ฅผ ์“ธ๋•Œ ์–ด๋Š ํƒ€์ด๋ฐ์— filter๋ฅผ ์“ฐ๊ณ  reduce๋ฅผ ์จ์•ผํ• ์ง€ ํ—ท๊ฐˆ๋ฆด ์ˆ˜ ์žˆ๋Š”๋ฐ ํ•ญ์ƒ "๋‚ด๊ฐ€ ๋ฌด์—‡์„ ๋งŒ๋“œ๋Š”๊ฐ€"์— ์ง‘์ค‘ํ•˜๋ฉด ๋œ๋‹ค.

 

์•„๋ž˜ ์˜ˆ์‹œ์—์„œ๋Š” ๊ฐ๊ฐ ์˜์ƒ์˜ ์ข…๋ฅ˜์— ๋”ฐ๋ผ ์นด์šดํŠธ๋ฅผ ๋ˆ„์ ์‹œํ‚ค๊ณ  ์‹ถ์—ˆ๊ธฐ ๋•Œ๋ฌธ์— catories๋ฅผ ๋งคํ•‘ํ–ˆ๊ณ  clothes๋ฅผ ์ „๋ถ€ ๋Œ๋ฉด์„œ ํ•ด๋‹นํ•˜๋Š” ๊ฒƒ์„ filter -> countํ–ˆ๋‹ค. 

 

import Foundation

func solution(_ clothes:[[String]]) -> Int {
    let types = clothes.compactMap{ $0.last! }
    let setType = Set(types)
    let categories = Array(setType)
    
    let counts = categories.map { category in
        return clothes.filter{ $0.last! == category }.count + 1
    }
    
    return counts.reduce(1, {$0 * $1}) - 1  
}

 

 ํ”ผ๋“œ๋ฐฑ

 

๋”•์…”๋„ˆ๋ฆฌ๋ฅผ for๋ฌธ์œผ๋กœ ์ ‘๊ทผํ•  ๋•Œ ํŠœํ”Œ์ฒ˜๋Ÿผ .์—ฐ์‚ฐ์ž๋กœ key๋‚˜ value์— ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

 

let dic: [String: Int] = ["a": 1, "b": 2]
for x in dic {
	print(x.1 terminator:" ") // output: 1 2
}