[Programmers] [Lv.1] [Swift] 모의고사

doyeonjeong_·2022년 8월 17일
0

프로그래머스

목록 보기
31/35
post-thumbnail

문제

모의고사

문제파악하기

  • 점수 [수포자 번호 : 맞은 개수]
  • 그 value에 1을 누적해가면서 각 수포자의 맞은 개수를 카운팅한다.

풀이

import Foundation

func solution(_ answers:[Int]) -> [Int] {
    let first = [1, 2, 3, 4, 5]
    let second = [2, 1, 2, 3, 2, 4, 2, 5]
    let third = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
    var scores = [Int:Int]()
    
    for i in 0 ..< answers.count {
        if answers[i] == first[i % first.count] { scores[1, default: 0] += 1 }
        if answers[i] == second[i % second.count] { scores[2, default: 0] += 1 }
        if answers[i] == third[i % third.count] { scores[3, default: 0] += 1 }
    }

    return scores.filter { $0.value == scores.values.max() }.keys.sorted()
}

🤔 FEEDBACK

  • 한참 Array에 정답 맞춘 개수 카운트해서 따로 만들어서 넣다가 이게 아닌 것 같아서 방법을 바꿨다.
  • scores[1, default: 0]은 scores[1] key가 없을 때 0으로 초기화

다른 풀이

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 }
}

Reference

profile
블로그 이사중 🚚 byukbyak.tistory.com

0개의 댓글