티스토리 뷰

programmers.co.kr/learn/courses/30/lessons/42840

나의 풀이

import Foundation

func solution(_ answers:[Int]) -> [Int] {
    
    let first: [Int] = [1, 2, 3, 4, 5]
    let second: [Int] = [2, 1, 2, 3, 2, 4, 2, 5]
    let third: [Int] = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
    
    var firstScore: Int = 0
    var secondScore: Int = 0
    var thirdScore: Int = 0
    
    for i in 0..<answers.count {
        let index1 = i % first.count
        if answers[i] == first[index1] {
            firstScore += 1
        }
        
        let index2 = i % second.count
        if answers[i] == second[index2] {
            secondScore += 1
        }
        
        let index3 = i % third.count
        if answers[i] == third[index3] {
            thirdScore += 1
        }
    }
    
    let dict: [Int: Int] = [1: firstScore, 2: secondScore, 3: thirdScore]
    
    let rank = dict
        .filter { $0.value == dict.values.max() }
        .map { $0.key }
        .sorted()
    
    return rank
}

 

다른 사람의 풀이

import Foundation

func solution(_ answers:[Int]) -> [Int] {
    let answer = (
        a: [1, 2, 3, 4, 5], // index % 5
        b: [2, 1, 2, 3, 2, 4, 2, 5], // index % 8
        c: [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] // index % 10
    )
    var point = [1:0, 2:0, 3:0]

    for (i, v) in answers.enumerated() {
        if v == answer.a[i % 5] { point[1] = point[1]! + 1 }
        if v == answer.b[i % 8] { point[2] = point[2]! + 1 }
        if v == answer.c[i % 10] { point[3] = point[3]! + 1 }
    }

    return point.sorted{ $0.key < $1.key }.filter{ $0.value == point.values.max() }.map{ $0.key }
}

배울 점

1. 처음부터 딕셔너리를 사용했으면 더 좋았음

 

댓글
공지사항