๐Ÿ“š

Array Average

Array Average
์‰ฌ์›€ ๋ฐฐ์—ด +10pts

Problem

Write a function that returns the average of all numbers in an array.

Examples

Input: average([1, 2, 3, 4, 5])
Output: 3

Explanation

์ด ๋ฌธ์ œ๋Š” **ํ•ฉ๊ณ„ ๊ณ„์‚ฐ**๊ณผ **ํ‰๊ท  ๊ณต์‹**์„ ๊ฒฐํ•ฉํ•˜์—ฌ ๋ฐฐ์—ด์˜ ํ‰๊ท ์„ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ํ•™์Šตํ•ฉ๋‹ˆ๋‹ค. **ํ‰๊ท  ๊ณต์‹** ํ‰๊ท  = ์ „์ฒด ํ•ฉ๊ณ„ / ์š”์†Œ ๊ฐœ์ˆ˜ **reduce๋กœ ํ•ฉ๊ณ„ ๊ตฌํ•˜๊ธฐ** `arr.reduce((sum, n) => sum + n, 0)` - ์ดˆ๊ธฐ๊ฐ’ 0๋ถ€ํ„ฐ ์‹œ์ž‘ - ๊ฐ ์š”์†Œ๋ฅผ ๋ˆ„์ ํ•˜์—ฌ ๋”ํ•จ **๋นˆ ๋ฐฐ์—ด ์ฒ˜๋ฆฌ** ๋นˆ ๋ฐฐ์—ด์˜ ๊ฒฝ์šฐ 0์œผ๋กœ ๋‚˜๋ˆ„๊ธฐ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ๋จผ์ € ์ฒดํฌํ•ฉ๋‹ˆ๋‹ค: ```javascript if (arr.length === 0) return 0; ``` **[1, 2, 3, 4, 5]์˜ ํ‰๊ท  ๊ณ„์‚ฐ*...

View detailed explanation โ†’

Key Concepts

ํ‰๊ท  ๊ณ„์‚ฐ ๊ณต์‹ reduce๋กœ ํ•ฉ๊ณ„ ๋นˆ ๋ฐฐ์—ด ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๋‚˜๋ˆ—์…ˆ ์—ฐ์‚ฐ
Time: O(n) Space: O(1)
solution.js
Ctrl + Enter
Run tests to see results here.