๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution/Programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ํ‰๊ท ๊ตฌํ•˜๊ธฐ Swift

by Fomagran ๐Ÿ’ป 2020. 3. 1.
728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ์„ค๋ช…

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

์ œํ•œ์‚ฌํ•ญ

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

์ž…์ถœ๋ ฅ ์˜ˆ

arr return
[1,2,3,4] 2.5
[5,5] 5

ํ’€์ด: reduce๋ฅผ ์ด์šฉํ•ด์„œ ์ฒ˜์Œ์‹œ์ž‘๊ฐ’์„ ์ •ํ•ด์ฃผ๊ณ  ๊ณ„์† ๋”ํ•ด์ฃผ๋„๋ก ์‹œํ‚ด. ๊ทธ๋ฆฌ๊ณ  ๊ทธ ํ•ฉ์„ ๋ฐฐ์—ด์˜ ๊ธธ์ด๋งŒํผ ๋‚˜๋ˆ”

์†Œ์ˆ˜์ ์ด ๋‚˜์˜ค๊ฒŒ ๋‚˜๋ˆ„๋ ค๋ฉด Double์„ Double๋กœ ๋‚˜๋ˆ ์ค˜์•ผ ์†Œ์ˆ˜์ ๊นŒ์ง€ ๋‚˜์˜ด.

1
2
3
4
func solution(_ arr:[Int]) -> Double {
    let sum = arr.reduce(0, { $0 + $1})
    return Double(sum)/Double(arr.count)
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€