알고리즘
[Swift 알고리즘] - 2016년 (Programmers)
Peppo
2022. 10. 12. 11:49
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/12901
문제 사진
내 풀이
let week: [String] = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]
let yoonDate = [
1: 5,
2: 1,
3: 2,
4: 5,
5: 0,
6: 3,
7: 5,
8: 1,
9: 4,
10: 6,
11: 2,
12: 4
]
func solution(_ a:Int, _ b:Int) -> String {
var index: Int = yoonDate[a]!
for _ in 1...b {
if index > 6 {
index = 0
}
index += 1
}
return week[index - 1]
}
- 딕셔너리 타입 yoonDate 를 1월 ~ 12월별 각 1일의 첫요일 Index를 value값으로 지정했다.
- solution 메서드안에 변수 index의 초기값으로 yoonDate[a]! --> 첫번째 파라미터 (월) 을 지정해주고 시작요일을 세팅한다.
- index가 7 을 넘어갈경우 0으로 바꿔 "SUN" 부터 시작하게 두번째 파라미터의 수만큼 roop를 돌린다.
- 최종 값을 return
다른사람의 풀이
// DateFormatter.. 👍
import Foundation
func solution(_ a:Int, _ b:Int) -> String {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd"
let date = dateFormatterGet.date(from:"2016-\(a)-\(b)")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EE"//"EE" to get short style
return dateFormatter.string(from:date!).uppercased()
}
배운것
딕셔너리를 이용해 알고리즘을 풀어본건 처음이다.
딕셔너리 (Dictionary)
key와 Value가 함께 저장되는 자료구조 이며, 정렬되지 않은 컬렉션 이다.
key, value 각각 타입은 같아야한다.
구조체!! Stack 에 저장
728x90