정수 배열 numbers가 매개변수로 주어집니다. numbers의 원소의 평균값을 return하도록 solution 함수를 완성해주세요.
0 ≤ numbers의 원소 ≤ 1,000
1 ≤ numbers의 길이 ≤ 100
정답의 소수 부분이 .0 또는 .5인 경우만 입력으로 주어집니다.
numbers result
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 5.5
[89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] 94.0
입출력 예 설명
입출력 예 #1
numbers의 원소들의 평균 값은 5.5입니다.
입출력 예 #2
numbers의 원소들의 평균 값은 94.0입니다.
function solution(numbers) {
let answer = 0;
for (let i = 0; i < numbers.length; i++) {
answer = answer + numbers[i];
}
return answer / numbers.length;
}
저는 이렇게 풀었고 다른 풀이를 보면
function solution(numbers) {
let answer = numbers.reduce(acc, cur => (acc + cur), 0) / numbers.length;
return answer;
}
예시로 들자면
// initialValue가 없을 경우
let number = [1, 2, 3, 4, 5];
number.reduce(reducer);
// 동작
// accumulator = 1, currentValue = 2, currentIndex = 1, result = 3
// accumulator = 3, currentValue = 3, currentIndex = 2, result = 6
// accumulator = 6, currentValue = 4, currentIndex = 3, result = 10
// accumulator = 10, currentValue = 5, currentIndex = 4, result = 15
// initialValue가 있을 경우
let number = [1, 2, 3, 4, 5];
number.reduce(reducer, 0);
// 동작
// accumulator = 0, currentValue = 1, currentIndex = 0, result = 1
// accumulator = 1, currentValue = 2, currentIndex = 1, result = 3
// accumulator = 3, currentValue = 3, currentIndex = 2, result = 6
// accumulator = 6, currentValue = 4, currentIndex = 3, result = 10
// accumulator = 10, currentValue = 5, currentIndex = 4, result = 15