일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Qualification Round
- Kubernetes
- nestedlists
- swift
- K8S
- 하늘과 바람과 별과 詩
- 정보과학과
- Python
- MySQL
- 해커랭크
- LEVEL 2
- on-prem
- 방통대 대학원 정보과학과
- Code Jam 2022
- ESXi 업데이트
- secondlowestgrade
- 프로그래머스
- hackerrank
- Code Jam
- C++
- 2022
- openebs
- 하늘과 바람과 별과 시
- 코딩테스트
- ingress-nginx
- 3D PRINTING
- 방송통신대학교 대학원 정보과학과
- GitLab
- 파이썬
Archives
- Today
- Total
공대생의 비망록
[프로그래머스][Lv. 2] 소수 찾기 Swift 풀이 본문
https://programmers.co.kr/learn/courses/30/lessons/42839
풀이
기존에 풀이하였던 소수 찾기 문제 (참고 : [프로그래머스][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 |
'Programming Language > Swift' 카테고리의 다른 글
[프로그래머스][Lv. 2] 가장 큰 수 Swift 풀이 (0) | 2022.05.17 |
---|---|
[프로그래머스][Lv. 2] 위장 Swift 풀이 (0) | 2022.05.17 |
[프로그래머스][Lv. 2] 행렬 테두리 회전하기 Swift 풀이 (0) | 2022.04.16 |
[프로그래머스][Lv. 2] 오픈채팅방 Swift 풀이 (0) | 2022.04.09 |
[프로그래머스][Lv. 2] 문자열 압축 Swift 풀이 (0) | 2022.04.08 |
Comments