Problem Solution/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/JS] ๋ฐฐ์—ด์˜ ํ‰๊ท ๊ฐ’

yuri lee 2023. 8. 25. 20:39
๋ฐ˜์‘ํ˜•

Problem Description

์ •์ˆ˜ ๋ฐฐ์—ด numbers๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. numbers์˜ ์›์†Œ์˜ ํ‰๊ท ๊ฐ’์„ returnํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

Restrictions

  • 0 ≤ numbers์˜ ์›์†Œ ≤ 1,000
  •  1 ≤ numbers์˜ ๊ธธ์ด ≤ 100 
  • ์ •๋‹ต์˜ ์†Œ์ˆ˜ ๋ถ€๋ถ„์ด .0 ๋˜๋Š” .5์ธ ๊ฒฝ์šฐ๋งŒ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

 

Input/Output Example

  • ์ž…์ถœ๋ ฅ ์˜ˆ #1 num1์ด 3, num2๊ฐ€ 2์ด๋ฏ€๋กœ 3์„ 2๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€ 1์„ return ํ•ฉ๋‹ˆ๋‹ค.
  • ์ž…์ถœ๋ ฅ ์˜ˆ #2 num1์ด 10, num2๊ฐ€ 5์ด๋ฏ€๋กœ 10์„ 5๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€ 0์„ return ํ•ฉ๋‹ˆ๋‹ค.

 

My solution

function solution(numbers) {
    const ret = numbers.reduce((a, b) => a + b, 0);
    result = ret/numbers.length
    const answer = result.toFixed(1)
    return answer;
}

 

์ดˆ๊ธฐ๊ฐ’: 0 ์ฒซ ๋ฒˆ์งธ ๋ฐ˜๋ณต: 0(๋ˆ„์ ๊ฐ’) + 1(ํ˜„์žฌ๊ฐ’) = 1 ๋‘ ๋ฒˆ์งธ ๋ฐ˜๋ณต: 1(๋ˆ„์ ๊ฐ’) + 2(ํ˜„์žฌ๊ฐ’) = 3 ์„ธ ๋ฒˆ์งธ ๋ฐ˜๋ณต: 3(๋ˆ„์ ๊ฐ’) + 3(ํ˜„์žฌ๊ฐ’) = 6 ๋„ค ๋ฒˆ์งธ ๋ฐ˜๋ณต: 6(๋ˆ„์ ๊ฐ’) + 4(ํ˜„์žฌ๊ฐ’) = 10 ์ตœ์ข… ๋ฐ˜ํ™˜๊ฐ’: 10

 


Reference: https://school.programmers.co.kr/learn/courses/30/lessons/120817

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

Array.prototype.reduce() - JavaScript | MDN

The reduce() method of Array instances executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across al

developer.mozilla.org

๋ฐ˜์‘ํ˜•