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

[Swift Algorithm] x๋งŒํผ ๊ฐ„๊ฒฉ์ด ์žˆ๋Š” n๊ฐœ์˜ ์ˆซ์ž Programmers(Lv.1)

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

ํ•จ์ˆ˜ solution์€ ์ •์ˆ˜ x์™€ ์ž์—ฐ์ˆ˜ n์„ ์ž…๋ ฅ ๋ฐ›์•„, x๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด x์”ฉ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆซ์ž๋ฅผ n๊ฐœ ์ง€๋‹ˆ๋Š” ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฆฌํ„ดํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์Œ ์ œํ•œ ์กฐ๊ฑด์„ ๋ณด๊ณ , ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ ์กฐ๊ฑด
  • x๋Š” -10000000 ์ด์ƒ, 10000000 ์ดํ•˜์ธ ์ •์ˆ˜์ž…๋‹ˆ๋‹ค.
  • n์€ 1000 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
x n answer
2 5 [2, 4, 6, 8, 10]
4 3 [4, 8, 12]
-4 2 [-4 , -8]

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution(_ x:Int, _ n:Int) -> [Int64] {
    var arr = [Int64]()
    var k = x
    var num = 0
    
    while num < n {
        arr.append(Int64(k))
        k += x
        num += 1
    }

    return arr
}
  • ์ž…๋ ฅ ๋ฐ›์€ n๊ฐ’ ๋งŒํผ, ๋นˆ ๋ฐฐ์—ด arr์— k๋ถ€ํ„ฐ x์”ฉ ๋ˆ„์ ๋˜๋Š” ์ˆ˜๋ฅผ append ํ•ด์ฃผ์—ˆ์Œ.

 

์ธ์ƒ์ ์ธ ํ’€์ด
func solution(_ x:Int, _ n:Int) -> [Int64] {
    return Array(1...n).map { Int64($0 * x) }
}
  • ๋ฆฌํ„ด ๋ฌธ์— ๋ฐ”๋กœ 1๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•ด์ฃผ๊ณ , map์„ ์ด์šฉํ•ด์„œ ๋ชจ๋“  ์š”์†Œ์— (๊ฐ’ * x)๋ฅผ ํ•ด์ฃผ์—ˆ์Œ.
  • ๋ฐฐ์—ด์— ๋จผ์ € 1๋ถ€ํ„ฐ n์— ํ•ด๋‹นํ•˜๋Š” ์ˆ˜๋ฅผ ๋„ฃ๊ณ , ๊ทธ ๋‹ค์Œ x๋ฅผ ๊ณฑํ•ด์ค€๋‹ค๋Š” ๊ฐœ๋….
    ๋‚˜๋Š” ๋นˆ ๋ฐฐ์—ด์— ์ฃผ์–ด์ง„ ์ˆ˜ ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜์—ฌ x๊ฐ’์„ ๋ˆ„์ ์‹œ์ผœ ์ค€๋‹ค๋Š” ๊ฐœ๋…์œผ๋กœ ์ƒ๊ฐํ–ˆ๋Š”๋ฐ,
    ์ด ํ’€์ด๋Š” ์ ‘๊ทผ ๋ฐฉ์‹๋ถ€ํ„ฐ ๋‚ด ํ’€์ด์™€ ์ฐจ์ด๊ฐ€ ์žˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • map ํ•จ์ˆ˜๋ฅผ ์ž์œ ๋กญ๊ฒŒ ์“ธ ์ˆ˜ ์žˆ์œผ๋ฉด ํ›จ์”ฌ ํšจ์œจ์ ์ธ ์ฝ”๋”ฉ์ด ๊ฐ€๋Šฅํ•  ๊ฒƒ ๊ฐ™๋‹ค.

 


 

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

func solution3(_ x:Int, _ n:Int) -> [Int64] {
    var arr = [Int64]()
    for i in 0..<n { arr.append(Int64(x+(x*i))) }
    return  arr
}
  • ๋กœ์ง์€ ์ฒซ ๋ฒˆ์งธ ํ’€์—ˆ์„ ๋•Œ์™€ ๋น„์Šทํ•˜์ง€๋งŒ, ํ›จ์”ฌ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์ž‘์„ฑํ–ˆ๋‹ค.

 


 

๋ฌธ์ œ

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

๋Œ“๊ธ€