코딩테스트 문제 풀기 Lv0 평균 구하기

휘루·2024년 6월 19일
0

코딩테스트

목록 보기
10/13

문제 설명

정수 배열 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;
}
  • for문을 돌려 i를 0부터(index 처음인 0부터) 시작, 평균은 전체 합산해서 전체의 갯수를 나눕니다.
  • 그러니 전체의 갯수인 numbers.length가 들어갑니다.
  • length만큼 증가해야 하니 (let i = 0; i < numbers.length; i++) 을 수식으로 씁니다.
  • 이제 answer에 값을 numbers의 [i] 갯수 만큼 합산해 넣습니다. answer = answer + numbers[i];
  • 이제 return하여 나누기를 연산합니다. return answer / numbers.length;

저는 이렇게 풀었고 다른 풀이를 보면

다른 분이 풀었던 또 다른 문제 풀이

function solution(numbers) {
	let answer = numbers.reduce(acc, cur => (acc + cur), 0) / numbers.length;
    
	return answer;
}
  • reduce를 사용해 numbers(acc, cur => (acc(누적계산) + cur(배열의 n번째 요소), 0);
  • numbers의 배열 속 acc로 전체 누적 계산을 cur(n번째 만큼) 합산 합니다.
  • 끝에 0은 initialValue라는 것인데 0이 있으면 0부터 합산 동작을 한다는 뜻입니다.

reduce

예시로 들자면

// 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
profile
반가워요

0개의 댓글