본문 바로가기
코딩테스트/프로그래머스

[프로그래머스] 완전탐색 : 모의고사 Kotlin

by 일상 속 둔치 2020. 10. 2.

모든 경우의 수를 비교해보는 완전탐색 문제이다.

 

이런 문제를 풀 때 패턴을 미리 배열로 선언해놓고 사용하면 편하다!

 

Pair를 사용하여 수포자 번호와 맞힌 문제의 수를 관리하였다.

 

답과 같으면 +1 해주고 해당 값으로 정렬하였다.

 

class Solution {
    fun solution(answers: IntArray): IntArray {
        var answer = mutableListOf<Int>()
        var first = intArrayOf(1,2,3,4,5)
        var second = intArrayOf(2,1,2,3,2,4,2,5)
        var third = intArrayOf(3,3,1,1,2,2,4,4,5,5)

        var cntList = mutableListOf<Pair<Int,Int>>(Pair(1,0),Pair(2,0),Pair(3,0))

        answers.mapIndexed { index, i ->
            if(i == first[index%first.size]){
                cntList.set(0,Pair(1,cntList.get(0).second+1)) 
            }
            if(i == second[index%second.size]){
                cntList.set(1,Pair(2,cntList.get(1).second+1))
            }
            if(i == third[index%third.size]){
                cntList.set(2,Pair(3,cntList.get(2).second+1))
            }
        }

        cntList.sortWith(Comparator { o1, o2 ->
            return@Comparator o2.second-o1.second
        })

        cntList.map {
            if(it.second == cntList[0].second){
                answer.add(it.first)
            }
        }
        answer.sort()

        return answer.toIntArray()
    }
}

댓글