CodeWars 코딩 문제 2021/01/08 - Calculate Variance

이호현·2021년 1월 8일
0

Algorithm

목록 보기
46/138

[문제]

Write a function which will accept a sequence of numbers and calculate the variance for the sequence.

The variance for a set of numbers is found by subtracting the mean from every value, squaring the results, adding them all up and dividing by the number of elements.

For example, in pseudo code, to calculate the variance for [1, 2, 2, 3].

mean = (1 + 2 + 2 + 3) / 4
=> 2

variance = ((1 - 2)^2 + (2 - 2)^2 + (2-2)^2 + (3 - 2)^2) / 4
=> 0.5

The results are tested after being rounded to 4 decimal places using Javascript's toFixed method.

(요약) 배열 요소를 이용해 분산을 구해라.

[풀이]

var variance = function(numbers) {
  const avg = numbers.reduce((acc, num) => acc += num, 0) / numbers.length;
  return numbers.map(num => (num - avg) * (num - avg)).reduce((acc, num) => acc += num, 0) / numbers.length;
};

평균을 구하고, 각 요소에 차의 제곱을 다 더하고 평균을 내면 됨.

profile
평생 개발자로 살고싶습니다

0개의 댓글