본문 바로가기
Algorithm/Programmers

[고득점 Kit (완전탐색)] 모의고사 (swift)

by 원만사 2021. 10. 11.
반응형

 

코딩테스트 연습 - 모의고사

수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 1번 문제부터 마지막 문제까지 다음과 같이 찍습니다. 1번 수포자가 찍는

programmers.co.kr

 

 

풀이


각각의 수포자의 정답 패턴을 배열에 담아둔다.

answers 배열을 for문으로 돌면서 각각의 수포자가 정답을 맞췄는지 체크 후에 가장 많은 문제를 맞힌 사람을 체크하여 res 배열에 담아 return 해준다.

 

코드


import Foundation

var first: [Int] = [1, 2, 3, 4, 5]
var second: [Int] = [2, 1, 2, 3, 2, 4, 2, 5]
var third: [Int] = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]

func solution(_ answers:[Int]) -> [Int] {
    
    var cnt: [Int] = [0, 0, 0]
    
    for i in 0..<answers.count {
        let answer: Int = answers[i]
        
        if answer == first[i % first.count] {
            cnt[0] += 1
        }
        
        if answer == second[i % second.count] {
            cnt[1] += 1
        }
        
        if answer == third[i % third.count] {
            cnt[2] += 1
        }
    }
    
    let max_cnt = max(cnt[0], max(cnt[1], cnt[2]))
    var res: [Int] = []
    
    for i in 0...2 {
        if max_cnt == cnt[i] {
            res.append(i+1)
        }
    }
    
    return res
}
반응형

댓글