공대생의 비망록

[프로그래머스][Lv. 2] 소수 찾기 Swift 풀이 본문

Programming Language/Swift

[프로그래머스][Lv. 2] 소수 찾기 Swift 풀이

myungsup1250 2022. 4. 27. 16:33

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

 

코딩테스트 연습 - 소수 찾기

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

programmers.co.kr

풀이

 

기존에 풀이하였던 소수 찾기 문제 (참고 : [프로그래머스][Lv. 1] 소수 찾기 Swift 풀이)와 풀이 방법은 크게 다르지 않다.

다만 입력으로 Int형 배열의 정수를 조합하여 생성할 수 있는 수 중 소수를 몇 개 만들 수 있는지 확인하면 된다.

그러나 Swfit에는 안타깝게도 조합/순열을 생성하는 빌트인 함수가 없다...

따라서 이를 생성하는 함수를 구현하였다. (참고 : )

이후 생성된 조합들을 Int 형 배열에 중복 없이 저장하는 과정을 거쳐, 소수를 판별하여 그 수를 반환한다.

 

끝!

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import Foundation
 
var combinations = [String]()
 
// numbers: numbers to make permutations
// currentNumber: Start with empty String when the func starts
func combination(numbers: [String], currentNumber: String) {
    if currentNumber != "" && !combinations.contains(currentNumber) {
        combinations.append(currentNumber)
    }
    
    for i in 0..<numbers.count {
        var newNumbers = numbers
        let newCurrentNumber = newNumbers.remove(at: i)
        combination(numbers: newNumbers, currentNumber: currentNumber + newCurrentNumber)
    }
}
 
func eratosthenes(_ num: Int-> Bool {
    let sqrtNum: Int = Int(sqrt(Double(num))) + 1
    for i in 2..<sqrtNum {
        if num % i == 0 {
            return false
        }
    }
    return true
}
 
func solution(_ numbers:String-> Int {
    let nums: [String= numbers.map { String($0) }
    combination(numbers: nums, currentNumber: "")
    var intCombs: [Int= [Int]()
    for comb in combinations {
        let cmb: Int = Int(comb)!
        if !intCombs.contains(cmb) {
            intCombs.append(cmb)
        }
    }
    
    var count: Int = 0
    for comb in intCombs {
        if comb < 2 { // 2 미만은 소수가 아니다
            continue
        }
        if eratosthenes(comb) {
            count += 1
        }
    }
        
    return count
}
cs
Comments