Algorithm/프로그래머스

[프로그래머스 스위프트] 위장

devKen 2022. 7. 31. 01:29

문제 요약

해시 중에서는 처음 스위프트 문제입니다. 지난번에 푼 문제와 같이 해시 카테고리이니 단순하게 for문으로 풀면 안 될 거 같습니다. 

해답

 

딕셔너리에 대한 이해와 key, Value를 다룰 줄 알면 쉽게 풀 수도 있었던 문제였습니다. 전 결국 다른 사람들의 답을 보고 풀었네요..

 

 

func solution(_ clothes:[[String]]) -> Int {
    var clothTypeSum: [String:Int] = [:]
    for cloth in clothes {
        if !clothTypeSum.keys.contains(cloth[1]) {
            clothTypeSum[cloth[1]] = 0
        }
    clothTypeSum[cloth[1]]? += 1
    }
    var cnt = 1
    for num in clothTypeSum.values {
        cnt *= (num + 1)
    }
return cnt - 1
}

by: https://jellysong.tistory.com/78?category=867432

 

import Foundation

func solution(_ clothes:[[String]]) -> Int {
    let types = clothes.compactMap({ $0.last })
    let typeSet = Set(types)
    let categories = Array(typeSet)

    let counts = categories.map({ category in
        return clothes.filter({ $0.last == category }).count + 1
    })

    return counts.reduce(1,  { $0 * $1 }) - 1
}

많은 사람들이 위와 같이 풀었던데 고차 함수를 이해하기에 적절할 예시라 생각합니다.