Kotlin/코딩테스트

[프로그래머스] 소수 찾기 - kotlin

깨노비 2023. 4. 21. 17:21
728x90
반응형

한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.

각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.

import kotlin.math.sqrt

class Solution {
    val useList = mutableListOf<Int>()
    val primeSet = mutableSetOf<Int>()
    
    fun solution(numbers: String): Int {
        makeNumber(numbers, StringBuilder("0"))

        return primeSet.size
    }

    tailrec fun makeNumber(numbers: String, temp: StringBuilder) {
        val number: Int = temp.toString().toInt()
        if (number > 1 && isPrimeNumber(number)) primeSet.add(number)

        if (numbers.length > useList.size) {
            for ((i, value) in numbers.withIndex()) {
                if (useList.contains(i)) continue

                useList.add(i)
                makeNumber(numbers, temp.append(value))
                useList.removeLast()
                temp.deleteCharAt(temp.length - 1)
            }
        }
    }

    fun isPrimeNumber(number: Int): Boolean {
        val last = sqrt(number.toDouble()).toInt()
        val set = mutableSetOf<Int>()
        var flag = true

        for (i in 2..last) {
            if (set.contains(i)) continue

            if (number % i == 0) {
                flag = false
                break
            } else {
                (i..last)
                    .filter { it % i == 0 }
                    .forEach { set.add(it) }
            }
        }

        return flag
    }
}
728x90
반응형