Algorithm

SwiftUI: 성격 유형 검사하기

songmoro 2023. 12. 17. 22:02

주어진 배열 검사해서 switch case로 처리, 다른 분 답 보니까 case로 분기 처리 안하고 기본 값에서 choice의 값 처리해서 풀 수 도 있네요.

 

func solution(_ survey:[String], _ choices:[Int]) -> String {
    // MARK: 같다면 R C J A
    
    var answer = ""
    var type: [String: Int] = [:]
    "R T C F J M A N".split(separator: " ").forEach {
        type[String($0)] = 0
    }
    
    for (index, choice) in choices.enumerated() {
        let negative = String(survey[index].first!)
        let positive = String(survey[index].last!)
        
        switch choice {
        case 1:
            type[negative]! += 3
        case 2:
            type[negative]! += 2
        case 3:
            type[negative]! += 1 
        case 5:
            type[positive]! += 1
        case 6:
            type[positive]! += 2
        case 7:
            type[positive]! += 3
        default:
            break
        }
    }
    
    answer.append(type["R"]! >= type["T"]! ? "R" : "T")
    answer.append(type["C"]! >= type["F"]! ? "C" : "F")
    answer.append(type["J"]! >= type["M"]! ? "J" : "M")
    answer.append(type["A"]! >= type["N"]! ? "A" : "N")
    
    return answer
}