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

[Swift Algoritm] ํ‰๊ท  ๊ตฌํ•˜๊ธฐ Programmers(Lv.1)

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

์ •์ˆ˜๋ฅผ ๋‹ด๊ณ  ์žˆ๋Š” ๋ฐฐ์—ด arr์˜ ํ‰๊ท ๊ฐ’์„ returnํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•ด๋ณด์„ธ์š”.

 

์ œํ•œ ์กฐ๊ฑด
  • arr๋Š” ๊ธธ์ด 1 ์ด์ƒ, 100 ์ดํ•˜์ธ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
  • arr์˜ ์›์†Œ๋Š” -10,000 ์ดํ•˜์ธ ์ •์ˆ˜์ž…๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
arr return
[1, 2, 3, 4] 2.5
[5, 5] 5

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution(_ arr:[Int]) -> Double {
    let result = Double(arr.reduce(0, +)) / Double(arr.count) 
    return result
}
  • reduce(0, +)๋ฅผ ์ด์šฉํ•ด์„œ arr ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์›์†Œ๋ฅผ ๋”ํ•ด์ฃผ๊ณ , arr.count๋กœ ๊ตฌํ•œ ๋ฐฐ์—ด์˜ ๊ธธ์ด๋กœ ๋‚˜๋ˆ„์–ด์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ๊ตณ์ด result ์ƒ์ˆ˜๋ฅผ ์„ ์–ธํ•˜์ง€ ์•Š๊ณ  ๋ฐ”๋กœ return๋ฌธ ํ•œ ์ค„์—์„œ ๋๋‚ด๋„ ๋์„ ๋“ฏ ์‹ถ๋‹ค.
  • reduce ๊ณ ์ฐจ ํ•จ์ˆ˜์˜ ์ •ํ™•ํ•œ ์˜๋ฏธ ๋ฐ ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์— ๋Œ€ํ•œ ๊ณต๋ถ€ ํ•„์š”!! ๋‹ค์Œ ๊ธ€์—์„œ ๋‹ค๋ค„์•ผ๊ฒ ๋‹ค.

 


 

๋ฌธ์ œ

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

๋Œ“๊ธ€