728x90
문제
정수 배열 numbers가 매개변수로 주어집니다. numbers의 원소의 평균값을 return하도록 solution 함수를 완성해주세요.
해결 과정
1. 배열의 합을 구한다.
2. 배열의 길이로 나눈다.
새롭게 알게된 점📝
배열의 합을 어떻게 구해야하나 구글링을 하여 문제를 해결했다.
참고했던 사이트: https://sentry.io/answers/how-to-find-the-sum-of-an-array-of-numbers/
How to find the sum of an array of numbers
The Problem You want to find the sum of an array of numbers. How do you do this with JavaScript? The Solution There are various ways to find the sum of an array…
sentry.io
다른 사람이 푼 문제풀이를 봤는데 .reduce를 이용해서 문제를 풀었다.
function solution(numbers) {
return (numbers.reduce((a, b) => a+b)) / numbers.length
}
정답
function solution(numbers) {
// 1. 배열의 합을 구한다.
let sum = 0;
for(let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
// 2. 배열의 길이로 나눈다.
let avg = sum / numbers.length;
return avg;
}
10m
728x90
'⌨️ 프로그래머스 > 코딩테스트 입문' 카테고리의 다른 글
[프로그래머스] 아이스 아메리카노 ☕ (1) | 2024.02.18 |
---|---|
[프로그래머스] 옷가게 할인 받기 👕👖 (0) | 2024.02.17 |
[프로그래머스] 피자 나눠 먹기(3) 🍕 (0) | 2024.02.17 |
[프로그래머스] 피자 나눠먹기(2) 🍕 (0) | 2024.02.17 |
[프로그래머스] 피자 나눠 먹기(1) 🍕 (0) | 2024.02.16 |