๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
3๏ธโƒฃ Swift/Problem Solving

[Swift Algorithm] 2016๋…„ Programmers(Lv.1)

by seolhee2750 2021. 6. 17.
๋ฌธ์ œ ์„ค๋ช…

2016๋…„ 1์›” 1์ผ์€ ๊ธˆ์š”์ผ์ž…๋‹ˆ๋‹ค. 2016๋…„ a์›” b์ผ์€ ๋ฌด์Šจ ์š”์ผ์ผ๊นŒ์š”? ๋‘ ์ˆ˜ a ,b๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ 2016๋…„ a์›” b์ผ์ด ๋ฌด์Šจ ์š”์ผ์ธ์ง€ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•˜์„ธ์š”. ์š”์ผ์˜ ์ด๋ฆ„์€ ์ผ์š”์ผ๋ถ€ํ„ฐ ํ† ์š”์ผ๊นŒ์ง€ ๊ฐ๊ฐ SUN,MON,TUE,WED,THU,FRI,SAT

์ž…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด a=5, b=24๋ผ๋ฉด 5์›” 24์ผ์€ ํ™”์š”์ผ์ด๋ฏ€๋กœ ๋ฌธ์ž์—ด "TUE"๋ฅผ ๋ฐ˜ํ™˜ํ•˜์„ธ์š”.

 

์ œํ•œ ์กฐ๊ฑด
  • 2016๋…„์€ ์œค๋…„์ž…๋‹ˆ๋‹ค.
  • 2016๋…„ a์›” b์ผ์€ ์‹ค์ œ๋กœ ์žˆ๋Š” ๋‚ ์ž…๋‹ˆ๋‹ค. (13์›” 26์ผ์ด๋‚˜ 2์›” 45์ผ๊ฐ™์€ ๋‚ ์งœ๋Š” ์ฃผ์–ด์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค)

 

์ž…์ถœ๋ ฅ ์˜ˆ
a b result
5 24 "TUE"

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution(_ a:Int, _ b:Int) -> String {
    let days = ["FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU"]
    let months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    var dayCount = 0 
    
    for i in 0..<a-1 {
        dayCount += months[i]
    }
    
    return days[(dayCount + b - 1) % 7]
}
  • 1์›” 1์ผ์ด ๊ธˆ์š”์ผ๋กœ ์ฃผ์–ด์กŒ์œผ๋ฏ€๋กœ, ๊ธˆ์š”์ผ๋ถ€ํ„ฐ ์š”์ผ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•ด์ฃผ์—ˆ๋‹ค.
  • ๋‹ฌ ๋ณ„ ๋‚ ์งœ๋ฅผ ์ €์ •ํ•œ ๋ฐฐ์—ด๋„ ๋”ฐ๋กœ ๋งŒ๋“ค์–ด์ฃผ์—ˆ๋‹ค.
  • ์ž…๋ ฅ๋œ ์›”์˜ ์ „ ๋‹ฌ๊นŒ์ง€์˜ ๋‚ ์งœ ์ˆ˜๋ฅผ ๋ˆ„์ ํ•ด์ฃผ์—ˆ๊ณ , ๋ฆฌํ„ด๋ฌธ์—์„œ ํ•ด๋‹น ์›”์˜ ์š”์ผ์„ ๊ตฌํ•ด ๋ฐ˜ํ™˜ํ•ด์ฃผ์—ˆ๋‹ค.

 

์ธ์ƒ์ ์ธ ํ’€์ด
func solution(_ a:Int, _ b:Int) -> String {
    let w = ["THU", "FRI", "SAT", "SUN", "MON", "TUE", "WED"]
    let monthDay = [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    let totalDay = monthDay[0..<a-1].reduce(0, +) + b

    return w[totalDay % 7]
}
  • ๋‚ด ํ’€์ด์˜ for๋ฌธ์„ reduce๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•œ ์ค„๋กœ ์ค„์—ฌ์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ๋ฐฐ์—ด ์•ˆ์˜ ์ˆ˜๋ฅผ ๋”ํ•  ๋•Œ๋Š” reduce๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๊ฐ„ํŽธํ•˜๋‹ค,!
  • ์œค๋…„ ๋ฌธ์ œ๋ฅผ ์—ฌ๊ธฐ์ €๊ธฐ์„œ ๋งŽ์ด ๋ฐœ๊ฒฌํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค,, ์ต์ˆ™ํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋„๋ก ๋งŽ์ด ์—ฐ์Šตํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค.

 


 

๐Ÿ– [ ์ถ”๊ฐ€ ] 1์ฃผ์ผ ํ›„ ๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ

func solution(_ a:Int, _ b:Int) -> String {
    let days = ["FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU"]
    let months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    return days[(months[0..<(a-1)].reduce(0, +) + b - 1) % 7]
}
  • reducea๋ฅผ ์ž˜ ํ™œ์šฉํ•˜์—ฌ ํ›จ์”ฌ ๊น”๋”ํ•˜๊ฒŒ ํ’€์—ˆ๋‹ค,!!

 


 

๋ฌธ์ œ

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

๋Œ“๊ธ€