본문 바로가기
note/language-kotlin

[programmers] Lv.1 로또의 최고 순위와 최저 순위(Kotlin 공부용)

by 눈부신음표 2022. 5. 8.
728x90

이번엔 간단해보여서 내 c++ 코드를 kotlin으로 바꿔보는 작업도 하고

추가로 c++ 사용자로서 신기해보이는 코드를 해석해봤다. (문제시 삭제하겠음!)

참고로 공부하는 용도였기 때문에 프로그래머스에 실행만 해봤지 채점은 안해봤다.

 

문제

https://programmers.co.kr/learn/courses/30/lessons/77484

 

코딩테스트 연습 - 로또의 최고 순위와 최저 순위

로또 6/45(이하 '로또'로 표기)는 1부터 45까지의 숫자 중 6개를 찍어서 맞히는 대표적인 복권입니다. 아래는 로또의 순위를 정하는 방식입니다. 1 순위 당첨 내용 1 6개 번호가 모두 일치 2 5개 번호

programmers.co.kr


참고 코드1 (내 c++ 코드)

https://jolly-note.tistory.com/25?category=1025701 

 

[programmers] Lv.1 로또의 최고 순위와 최저 순위(c++)

빠르게 완료 for문 하나로 해결해서 만족스러움 :) 더보기 #include using namespace std; vector solution(vector lottos, vector win_nums) { sort(lottos.begin(), lottos.end()); sort(win_nums.begin(), win_..

jolly-note.tistory.com

 

변환

class Solution {
    fun solution(lottos: IntArray, win_nums: IntArray): IntArray {
        // sort는 변경 가능한 list, sorted는 변경 불가능한 list
        val sortedLottos = lottos.toList().sorted()
        val sortedWinNums = win_nums.toList().sorted()

        var idx: Int = 0
        var cnt: Int = 0
        var same: Int = 0
        // for(i: Int in 0 .. 5){
        for(i: Int in 0 until 6){
            if(sortedLottos[i] == 0){
                cnt += 1
                continue
            }
            while(sortedLottos[i] > sortedWinNums[idx])
                idx += 1

            if(sortedLottos[i] == sortedWinNums[idx])
                same += 1
        }

        // 원소를 추가하기 위해서 mutable로 지정
        var answer: MutableList<Int> = mutableListOf<Int>()     
        answer.add(if(same == 0 && cnt == 0) 6 else 7-(same+cnt))
        answer.add(if(same == 0) 6 else 7-same)
        return answer.toIntArray()
    }
}
728x90

참고 코드2(다른 분 코드)

https://velog.io/@nightlyherb/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EB%A1%9C%EB%98%90%EC%9D%98-%EC%B5%9C%EA%B3%A0-%EC%88%9C%EC%9C%84%EC%99%80-%EC%B5%9C%EC%A0%80-%EC%88%9C%EC%9C%84-in-Kotlin

 

[프로그래머스] 로또의 최고 순위와 최저 순위 in Kotlin

Kotlin의 Enum을 사용해보았습니다.

velog.io

 

해석

// enum class : 상수를 집합으로 관리, 따로 숫자를 할당하지 않으면 name과 ordinal을 사용해서 이름과 선언값을 알 수 있음.
enum class LottoResult(val intValue: Int){
    FIRST(1),
    SECOND(2),
    THIRD(3),
    FOURTH(4),
    FIFTH(5),
    SIXTH(6); // semicolon 주의

    companion object{ // java의 static처럼 동작 -> 클래스명.변수로 접근 가능
        fun fromMatchCount(count: Int): LottoResult?{ // ?은 null일 수 있음을 의미, !!는 null이 아님을 의미
            return when(count){ // when: 인자가 없어도 됨, 화살표 왼쪽은 조건, 오른쪽은 조건을 만족했을 때 수행할 문장
                0, 1->SIXTH
                2->FIFTH
                3->FOURTH
                4->THIRD
                5->SECOND
                6->FIRST
                else->null // 조건과 일치하는게 없으면 else
                // switch 문과 비슷하지만 break가 필요없다.
            }
        }

        fun fromMatchCountOrThrow(count: Int): LottoResult{
            return fromMatchCount(count)
                ?: throw IllegalArgumentException("Match count not in 0..6")
                // ?:는 좌항이 null이면 우항을 수행하라는것
        }
    }
}

class Solution {
    fun solution(lottos: IntArray, win_nums: IntArray): IntArray {
        val matchCount = (lottos.toSet() intersect win_nums.toSet()).size // union: 합집합, subtract: 차집합, intersect: 교집합
        println(matchCount)

        val unknownCount = lottos.count{it==0} // count: 조건에 일치하는 원소들의 개수 반환

        val worstResult = LottoResult.fromMatchCountOrThrow(matchCount)
        val bestResult = LottoResult.fromMatchCountOrThrow(matchCount+unknownCount)
        println(worstResult.toString() + " " + worstResult.intValue.toString())
        println(bestResult.toString() + " " + bestResult.intValue.toString())
        return intArrayOf(bestResult.intValue, worstResult.intValue)
    }
}
728x90

댓글