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

[Swift Algorithm] ์•ฝ์ˆ˜์˜ ๊ฐœ์ˆ˜์™€ ๋ง์…ˆ Programmers(Lv.1)

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

๋‘ ์ •์ˆ˜ left์™€ right๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. left๋ถ€ํ„ฐ right๊นŒ์ง€์˜ ๋ชจ๋“  ์ˆ˜๋“ค ์ค‘์—์„œ, ์•ฝ์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ง์ˆ˜์ธ ์ˆ˜๋Š” ๋”ํ•˜๊ณ , ์•ฝ์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ํ™€์ˆ˜์ธ ์ˆ˜๋Š” ๋บ€ ์ˆ˜๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ ์กฐ๊ฑด
  • 1 ≤ left  right ≤ 1,000

 

์ž…์ถœ๋ ฅ ์˜ˆ
left right result
13 17 43
24 27 52

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import Foundation

func solution(_ left:Int, _ right:Int) -> Int {
    var result = 0
    for i in left...right {
        var count = 0
        for j in 1...i {
            if i % j == 0 { count += 1 }
        }
        count % 2 == 0 ? (result += i) : (result -= i)
    }
    return result
}
  • ์–ด์ฐจํ”ผ left๋Š” right๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฏ€๋กœ ๋”ฐ๋กœ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ํ•ด ์ค„ ํ•„์š” ์—†์ด, ๋ฐ”๋กœ left...right๋กœ ๋ฐ˜๋ณต๋ฌธ์„ ์ž‘์„ฑํ–ˆ๋‹ค.
  • left๋ถ€ํ„ฐ right๊นŒ์ง€ ๋ชจ๋“  ์ˆ˜๋ฅผ 1๋ถ€ํ„ฐ ํ•ด๋‹น ์ˆ˜๊นŒ์ง€๋กœ ๋‚˜๋ˆ ๋ณด๋ฉฐ ์•ฝ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•ด์ฃผ์—ˆ๋‹ค.
  • ์•ฝ์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ง์ˆ˜๋ฉด ๋”ํ•ด์ฃผ๊ณ , ํ™€์ˆ˜๋ฉด ๋นผ์ฃผ๋Š” ๊ฒƒ์„ ๋ฐ˜๋ณตํ•ด์ฃผ์–ด ๋ˆ„์ ๋œ result ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ด์ฃผ์—ˆ๋‹ค.

 

์ธ์ƒ์ ์ธ ํ’€์ด
func solution(_ left: Int, _ right: Int) -> Int {
    return (left...right).map { i in (1...i).filter { i % $0 == 0 }.count % 2 == 0 ? i : -i }.reduce(0, +)
}
  • ๊ฐ€๋…์„ฑ ์ธก๋ฉด์—์„œ ๋ณด๋ฉด ์ข‹์€ ์ฝ”๋“œ์ธ์ง€๋Š” ์ž˜ ๋ชจ๋ฅด๊ฒ ์ง€๋งŒ, ๊ณ ์ฐจ ํ•จ์ˆ˜ ์‚ฌ์šฉ ๋ถ€๋ถ„์—์„œ ๋ฐฐ์šธ์ ์ด ๋งŽ์•„ ๊ฐ€์ ธ์™€๋ดค๋‹ค.
  • ์šฐ์„  (left...right).map ์ฒ˜๋Ÿผ ๋ฐ”๋กœ ๋ฒ”์œ„์— map์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์ด ๊ต‰์žฅํžˆ ์‹ ๊ธฐํ–ˆ๋‹ค,,
  • ํ•œ ์ค„์— map, filter, reduce๊ฐ€ ๋ชจ๋‘ ๋“ค์–ด๊ฐ„ ์ฝ”๋“œ,, ์—ญ์‹œ ํ™œ์šฉํ•  ์ ์ด ๋งŽ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ๊ณ ์ฐจํ•จ์ˆ˜๋ฅผ ์ ์ ˆํžˆ ์ž˜ ์„ž์–ด ์ž‘์„ฑํ–ˆ๋‹ค๋ฉด ๋” ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์ฝ”๋“œ๋ฅผ ์™„์„ฑํ•  ์ˆ˜ ์žˆ์—ˆ์„ ๊ฒƒ ๊ฐ™๋‹ค.

 


 

๋ฌธ์ œ

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

๋Œ“๊ธ€